sed
sed (Stream Editor) reads text line by line and applies editing commands such as substitute, delete, and insert. It is the standard tool for scripted find-and-replace in files and streams.
Understanding sed
What Is sed Used For?
sed applies edits non-interactively, which makes the same change repeatable across many files or inside a pipeline. The most common use is substitution, for example turning a config template into a production file.
sed 's/localhost/prod-db.internal/g' config.template > config.prodHow sed Processes Input
sed reads one line into a pattern space, applies your commands, prints the result, and moves to the next line. In s/old/new/, only the first match per line changes unless you add the g flag.
Practical sed Commands
sed 's/localhost/10.0.2.100/g' config.yaml # replace all per linesed 's/error/ERROR/gI' app.log # case-insensitive (GNU)sed 's|/old/path|/new/path|g' config.yaml # other delimiter for paths sed -i 's/debug: true/debug: false/' app.yaml # edit in placesed -i.bak 's/debug: true/debug: false/' app.yaml # in place with backup sed '/^#/d' config.yaml # drop comment linessed '/^$/d' config.yaml # drop blank linessed -n '10,20p' app.log # print lines 10 to 20sed -n '/START/,/END/p' file.txt # print a range sed '/^\[Service\]/a Restart=on-failure' app.service # append after matchsed -i '/PasswordAuthentication yes/s/^/#/' /etc/ssh/sshd_configsed -e 's/localhost/10.0.2.100/g' -e 's/5432/5433/g' config.yamlTroubleshooting sed
| Symptom | Command | What to Check |
|---|---|---|
| Not substituting | Run without -i first |
Preview the output |
| Special chars unmatched | Escape \. \* |
Regex metacharacters |
-i fails on macOS |
sed -i '' ... |
BSD sed needs a suffix argument |
Common MistakeUsing
sed -ibefore previewing. One wrong regex can corrupt a config file. Run without-ifirst, or use-i.bakto keep a backup.
TipWhen a pattern contains slashes, pick another delimiter such as
|,,, or#.
RememberCase-insensitive
I,\+, and some other features are GNU sed extensions. Scripts that must run on macOS or BusyBox need testing there.
Frequently Asked Questions
Why use sed instead of editing a file by hand?
sed is non-interactive, so the same edit runs identically across many files or in CI and config templating. That makes changes reproducible and scriptable.
How does sed -i differ between Linux and macOS?
GNU sed accepts `-i` alone or `-i.bak`. BSD sed on macOS requires an argument, so you write `-i ''` for no backup. For portable scripts, write to a temp file and move it into place.
Why did my sed replace only the first match on each line?
Without the `g` flag, `s/old/new/` substitutes just the first occurrence per line. Add `g` for all occurrences.