Understanding sed and awk in Linux: A Comparison with Examples

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:

  1. Search and Replace:
   sed 's/apple/orange/' filename
  1. Print Specific Lines:
   sed -n '/Linux/p' filename
  1. Delete Lines:
   sed '/error/d' filename
  1. Substitute with Regular Expression:
   sed 's/^word/new_word/' filename
  1. Append and Insert:
   sed 'a\Additional text' filename
   sed 'i\Additional text' filename

awk:

Basic Syntax:

awk 'pattern { action }' filename

Examples:

  1. Print Specific Columns:
   awk '{print $2}' filename
  1. Filter Rows based on Condition:
   awk '$1 > 10' filename
  1. Calculate and Print Sum:
   awk '{sum += $2} END {print sum}' filename
  1. Pattern Matching with Actions:
   awk '/error/ {print}' filename
  1. 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.