Text manipulation is a fundamental aspect of working in the Linux command line, and two powerful tools, sed
(stream editor) and awk
(text processing tool), play key roles in this domain. In this guide, we’ll explore the differences between sed
and awk
along with examples to illustrate their use cases.
sed
(Stream Editor):
Basic Syntax:
sed [options] 'script' input-file
Examples:
- Search and Replace:
sed 's/apple/orange/' filename
- Print Specific Lines:
sed -n '/Linux/p' filename
- Delete Lines:
sed '/error/d' filename
- Substitute with Regular Expression:
sed 's/^word/new_word/' filename
- Append and Insert:
sed 'a\Additional text' filename
sed 'i\Additional text' filename
awk
:
Basic Syntax:
awk 'pattern { action }' filename
Examples:
- Print Specific Columns:
awk '{print $2}' filename
- Filter Rows based on Condition:
awk '$1 > 10' filename
- Calculate and Print Sum:
awk '{sum += $2} END {print sum}' filename
- Pattern Matching with Actions:
awk '/error/ {print}' filename
- Print Specific Fields with Delimiter:
awk -F',' '{print $1, $3}' filename
Comparison:
sed
is designed for stream editing:- Ideal for basic text transformations and substitutions.
- Works line by line and modifies the input stream.
- Suitable for quick edits and one-time tasks.
awk
is a more comprehensive text-processing tool:- Ideal for data extraction, processing, and reporting.
- Processes input data in a structured manner, dividing it into fields.
- Allows for complex text manipulation using conditions and actions.
Both sed
and awk
are versatile and can be used in combination to achieve more complex text manipulation tasks.
Understanding the specific strengths of each tool helps in selecting the right one for the job at hand.