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:
old with new in each line.- Use
g flag for global replacement:2. Deletion (d)¶
Remove lines matching a pattern:
pattern.- Delete line 5:
3. Insertion (i)¶
Add text before a line:
New line before line 3.
4. Printing (p)¶
Print matched lines:
-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:
- Edit lines 3–5:
Patterns and Ranges¶
Combine patterns with ranges:
start and end.
Substitution with Regular Expressions¶
sed supports regex for flexible pattern matching:
Case-Insensitive Replacement¶
-I flag makes the match case-insensitive.
Replacing Entire Lines¶
- Matchespattern, then replaces the entire line with replacement.
Advanced Techniques¶
Multiple Commands¶
Chain operations with semicolons or newlines:
Holding Area and Registers¶
Use h, H, x, and G to manipulate a "hold space" for complex edits:
Key Takeaways¶
sedis a line-oriented stream editor for text transformation.- Core commands include
s(substitute),d(delete),i(insert), andp(print). - Use address ranges to target specific lines or patterns.
- Flags like
gandIenhance substitution flexibility. - Combine multiple commands for complex text processing workflows.