Skip to content

sed Fundamentals

Stream editing with sed (stream editor) enables powerful text transformation by processing input line-by-line. It’s ideal for search-and-replace operations, pattern matching, and file manipulation without requiring full programming. sed is particularly useful for automating repetitive text edits in scripts or pipelines.


Basic Operations and Commands

sed uses a simple syntax with single-letter commands to modify text. Common operations include:

1. Substitution (s)

Replace patterns in lines:

sed 's/old/new/' file.txt
- Replaces the first occurrence of old with new in each line.
- Use g flag for global replacement:
sed 's/old/new/g' file.txt

2. Deletion (d)

Remove lines matching a pattern:

sed '/pattern/d' file.txt
- Deletes lines containing pattern.
- Delete line 5:
sed '5d' file.txt

3. Insertion (i)

Add text before a line:

sed '3i\New line' file.txt
- Inserts New line before line 3.

4. Printing (p)

Print matched lines:

sed -n '/pattern/p' file.txt
- -n suppresses automatic output; p prints only matching lines.


Address Ranges and Context

sed allows targeting specific lines or ranges:

Line Numbers

  • Edit line 2:
    sed '2s/old/new/' file.txt
    
  • Edit lines 3–5:
    sed '3,5s/pattern/replacement/' file.txt
    

Patterns and Ranges

Combine patterns with ranges:

sed '/start/,/end/s/pattern/replacement/' file.txt
- Applies substitution between lines matching start and end.


Substitution with Regular Expressions

sed supports regex for flexible pattern matching:

Case-Insensitive Replacement

sed 's/Pattern/replacement/I' file.txt
- I flag makes the match case-insensitive.

Replacing Entire Lines

sed '/pattern/s/.*/replacement/' file.txt
- Matches pattern, then replaces the entire line with replacement.


Advanced Techniques

Multiple Commands

Chain operations with semicolons or newlines:

sed -e 's/old/new/' -e 'd' file.txt
Or:
sed '/pattern/{s/old/new/;p}' file.txt

Holding Area and Registers

Use h, H, x, and G to manipulate a "hold space" for complex edits:

sed -n 'h;G;p' file.txt
- Stores line in hold space, appends newline, and prints.


Key Takeaways

  • sed is a line-oriented stream editor for text transformation.
  • Core commands include s (substitute), d (delete), i (insert), and p (print).
  • Use address ranges to target specific lines or patterns.
  • Flags like g and I enhance substitution flexibility.
  • Combine multiple commands for complex text processing workflows.