sed — stream editor — rewrites text as it flows past. Its name is the whole job description: unlike an editor you open, sed applies edits to a stream, which makes it the tool of choice for scripted, repeatable changes across files and pipelines.
The substitution everyone uses #
$ echo "deploy to prod" | sed 's/prod/staging/'
deploy to staging
The pattern reads s/old/new/. Applied to a file, the change streams to the terminal; the file itself is untouched until you ask for it:
$ sed -i.bak 's/localhost/aospix.com/' app.conf
-i writes the file back, and .bak keeps the original beside it — cheap insurance on config edits.
Global, selective, and deleted lines #
By default sed replaces the first match per line. A trailing g handles every match, and line addresses narrow the scope:
$ sed 's/error/fault/g' app.log
$ sed '10,20s/#/;/g' notes.txt
Deleting lines rounds out the daily trio:
| Command | Effect |
|---|---|
sed 's/a/b/' | Replace first a per line |
sed 's/a/b/g' | Replace all matches per line |
sed '3d' file | Delete line 3 |
sed '/^#/d' file | Delete comment lines |
sed -n '5,8p' file | Print only lines 5–8 |
sed '/error/!d' file | Keep only matching lines |
That last row is territory grep usually owns — reach for grep when you are only filtering, and for sed when you are changing.
Real examples #
Strip comments and blank lines from a config for a clean view:
$ sed -e 's/#.*//' -e '/^\s*$/d' /etc/ssh/sshd_config
Swap a setting across many files at once:
$ for f in conf.d/*.conf; do sed -i 's/^Port .*/Port 2222/' "$f"; done
For column-aware edits rather than pattern edits, awk is the right neighbour, and for combined pipelines see unix pipes in practice. More from the terminal notes series lands weekly.
