The Linux sed Command: Stream Editing Reality
The Linux sed Command: Stream Editing Reality
I needed to replace "localhost" with "production-db" in 500 configuration files across 50 servers. "Just use sed," they said. Two hours later, I had done it manually—sed's in-place editing scared me.
Let me share what I learned about sed—safely.
First sed Commands
Replace first occurrence
sed 's/old/new/' file.txt
Replace first "old" with "new" in each line.
Replace all occurrences
sed 's/old/new/g' file.txt
Replace every occurrence (global).
In-place edit
sed -i 's/old/new/g' file.txt
-i = in-place. DANGEROUS—backup first!
Backup before in-place
sed -i.bak 's/old/new/g' file.txt
Creates file.txt.bak.
sed Address Ranges
Line numbers
sed '1,5 s/old/new/' file.txt
Only lines 1-5.
Pattern range
sed '/start/,/end s/old/new/' file.txt
From /start/ to /end/.
Every nth line
sed '1~2 s/old/new/' file.txt
Every other line.
sed Commands That Work
Print lines 10-20
sed -n '10,20p' file.txt
-n suppresses default output.
Delete lines 1-5
sed '1,5d' file.txt
Delete first 5 lines.
Delete blank lines
sed '/^$/d' file.txt
Delete empty lines.
Delete comments
sed '/^#/d' file.txt
Delete comment lines.
Insert line before
sed '1i\new line' file.txt
Insert at beginning.
Append line after
sed '$a\last line' file.txt
Append at end.
Print with line numbers
sed '=' file.txt | paste - -
sed Flags Reference
| Flag | Meaning |
|---|---|
| g | Global (all) |
| p | |
| d | Delete |
| i | Insert before |
| a | Append after |
| w | Write to file |
The sed Command Builder
Building sed commands—the sed Command Builder:
- Pattern builder with test preview
- In-place vs stdout clearly shown
- Safety warnings
Safety Rules
-
Always use -i.bak — have a backup.
-
Test with stdout first — remove the -i.
-
Use absolute paths — avoid mistakes.
-
Escape special chars — ., /, etc.
-
Check line numbers — before range edits.
Common sed Patterns
Replace in specific files
find . -name "*.conf" -exec sed -i.bak 's/old/new/g' {} \;
Replace across servers
ansible all -m shell -a "sed -i.bak 's/old/new/g' file.txt"
Conditional replace
sed '/pattern/s/old/new/g' file.txt
Replace only in matching lines.
Lessons Learned
-
Use -i.bak — safety first.
-
Test without -i — see output first.
-
Escape special characters — in patterns.
-
sed is line-oriented — works line by line.
-
Use awk for complex — sed is for simple.
Conclusion: sed Is Powerful
sed is stream editor—fast for simple replacements across many files.
The sed Command Builder makes building sed easy.
