sed
Overview
sed (stream editor) transforms text line by line — substitute, delete, print, and simple inserts — without opening an interactive editor. GNU sed is common on Linux.
Syntax
sed [options] 'script' [file...]
sed [options] -e 'script' -e 'script' [file...]
sed [options] -f script.sed [file...]Common Options
| Option | Description |
|---|---|
-n |
Quiet; only explicit prints |
-E / -r |
Extended regex |
-i[SUFFIX] |
In-place edit (optional backup suffix) |
-e |
Multiple scripts |
-f |
Script file |
Common Commands (in script)
| Cmd | Meaning |
|---|---|
s/pat/repl/flags |
Substitute (g, i, p) |
d |
Delete line |
p |
|
a/i/c |
Append/insert/change |
q |
Quit |
Safety
sed -i rewrites files — keep backups (-i.bak) until trusted. Quoting matters: prefer single quotes around scripts; use '\'' to embed a single quote.
Examples with Explanations
Substitute first match per line
sed 's/foo/bar/' file.txtGlobal substitute
sed 's/foo/bar/g' file.txtExtended regex
sed -E 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/IP/g' access.logDelete matching lines
sed '/^#/d; /^$/d' config.txtPrint only matches (like grep with rewrite)
sed -n 's/.*ERROR: //p' app.logIn-place with backup
sed -i.bak 's/Enable=false/Enable=true/' app.confLine ranges
sed -n '10,20p' file.txt
sed '1,5d' file.txtMultiple expressions
sed -e 's/\r$//' -e 's/[ \t]\+$//' file.txtNotes & Pitfalls
- Default regex is BRE;
+/|need escapes unless-E.
&in replacement is the whole match; use\&for literal.
- Binary files: do not
sed -iblindly.
- Complex multi-line edits are awkward — consider
perl -0peor an editor.
Additional Resources
man sed
- GNU sed manual