sed commands and flags reference
Complete reference for sed commands (s, d, p, i, a), flags (-i, -n, -e), and address ranges.
sed commands and flags reference
Complete reference for sed commands (s, d, p, i, a), flags (-i, -n, -e), and address ranges.
sed Command-Line Flags
| Flag | Description | Example |
|---|---|---|
-i [EXT] | Edit files in place. GNU:
-i (no backup) or
-i.bak. BSD:
-i '' or
-i .bak. | sed -i 's/old/new/g' file |
-n | Suppress default output. Print only lines selected by
p command. | sed -n '5,10p' file |
-e SCRIPT | Add a script (command) to execute. Allows multiple commands. | sed -e 's/a/b/' -e 's/c/d/' file |
-E or
-r | Use extended regular expressions (no backslash escaping for groups). | sed -E 's/(foo)/\1bar/' file |
-f FILE | Read sed commands from a file. | sed -f script.sed file |
sed Editing Commands
| Command | Description | Example |
|---|---|---|
s/pat/repl/flags | Substitute — replace
pat with
repl.
g flag replaces all matches per line. | s/old/new/g |
d | Delete the matched line(s). | /^#/d deletes comment lines |
p | Print the matched line(s). Use with
-n to print only matching lines. | -n '/error/p' |
i TEXT | Insert
TEXT before the matched line. | /pattern/i New line above |
a TEXT | Append
TEXT after the matched line. | /pattern/a New line below |
c TEXT | Replace the matched line with
TEXT. | /old line/c new line |
y/SRC/DST/ | Transliterate characters (like
tr). | y/abc/ABC/ |
q | Quit sed after processing the current line. | 10q quits after line 10 |
sed Address Ranges
| Address | Description | Example |
|---|---|---|
N | Line number N. | 3d deletes line 3 |
$ | Last line. | $d deletes the last line |
N,M | Lines N through M. | 10,20s/old/new/ |
/regex/ | Lines matching the regex. | /error/d |
N,/regex/ | From line N to the next line matching regex. | 1,/END/d |
/start/,/end/ | From line matching
start to line matching
end. | /BEGIN/,/END/p |
sed Substitution Flags
| Flag | Description | Example |
|---|---|---|
g | Replace all matches on the line (not just the first). | s/old/new/g |
N | Replace only the Nth match. | s/old/new/2 replaces the 2nd match |
p | Print the line if a substitution was made. | s/old/new/p |
w FILE | Write the line to FILE if a substitution was made. | s/old/new/w matches.txt |
I | Case-insensitive matching (GNU sed only). | s/error/ERROR/Ig |