sed Basics
sed is a stream editor. Its most common use: find and replace.
Basic Substitution
Syntax: s/pattern/replacement/
Replace in Files
This prints the result but doesn't modify the file.
Modify File In-Place
-i edits the file in place.
Backup First
-i is dangerous - no undo. Create a backup:
sed -i.bak 's/old/new/' file.txt
This creates file.txt.bak before modifying.
Replace All Occurrences
By default, sed replaces only the first match per line:
g = global (all occurrences).
Case-Insensitive
i flag for case-insensitive.
Using Different Delimiters
When your pattern contains /, use a different delimiter:
You can use |, #, @, or any character.
Delete Lines
Print Specific Lines
-n suppresses default output, p prints.
Real-World Examples
Change Config Values
Remove Comments
Remove Empty Lines
Add Prefix to Lines
Replace in Multiple Files
Capture Groups
For complex replacements:
\(pattern\) captures, \1 references it.
Extended Regex
Use -E for easier regex syntax:
echo 'hello world' | sed -E 's/(hello) (world)/\2 \1/'
How do you replace ALL occurrences of 'old' with 'new' in a file?
Quick Reference
| Command | Effect |
|---|---|
s/old/new/ | Replace first occurrence |
s/old/new/g | Replace all occurrences |
s/old/new/gi | Replace all, case-insensitive |
-i | Edit file in place |
-i.bak | Backup before editing |
/pattern/d | Delete matching lines |
-n '5p' | Print only line 5 |
Key Takeaways
sed 's/old/new/'replaces first occurrence per line- Add
gfor global replacement -iedits in place (dangerous without backup!)-i.bakcreates backup before modifying- Use different delimiters when patterns contain
/ sed '/pattern/d'deletes matching lines
Congratulations! You've completed Chapter 4: Text Manipulation.
Next chapter: Pipes and Redirection - the power of connecting commands.