Skip to main content

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.

Bash
sed 's/localhost/prod-db.internal/g' config.template > config.prod

How 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.

flowchart LR A[Input line] --> B[Pattern space] B --> C[Apply commands] C --> D[Print result] D --> A

Practical sed Commands

Bash
sed 's/localhost/10.0.2.100/g' config.yaml # replace all per line
sed '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 place
sed -i.bak 's/debug: true/debug: false/' app.yaml # in place with backup
sed '/^#/d' config.yaml # drop comment lines
sed '/^$/d' config.yaml # drop blank lines
sed -n '10,20p' app.log # print lines 10 to 20
sed -n '/START/,/END/p' file.txt # print a range
sed '/^\[Service\]/a Restart=on-failure' app.service # append after match
sed -i '/PasswordAuthentication yes/s/^/#/' /etc/ssh/sshd_config
sed -e 's/localhost/10.0.2.100/g' -e 's/5432/5433/g' config.yaml

Troubleshooting 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 Mistake

Using sed -i before previewing. One wrong regex can corrupt a config file. Run without -i first, or use -i.bak to keep a backup.

Tip

When a pattern contains slashes, pick another delimiter such as |, ,, or #.

Remember

Case-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.

Found a mistake, an outdated step or a broken link?