sed
sed is a non-interactive stream editor: it reads input line by line into a buffer called the pattern space, applies a script of editing commands, and writes the result out. It excels at find-and-replace, deleting or printing selected lines, and multi-line transforms via the hold space. This page is a searchable, offline reference to sed’s addresses, commands, substitute flags and command-line options, each with a working example.
How it works
Every sed command may be prefixed with an address that selects which lines it applies to:
- Addresses can be a line number
3, the last line$, a regex/re/, a range2,5or/a/,/b/, GNU step form1~2, or a negated formaddr!. - The substitute command
s/regex/replacement/flagsis the workhorse. Flags includeg(all matches), a numberN(the N-th match),p(print on change),i(case-insensitive) andm(multi-line). In the replacement,&is the whole match and\1..\9are captured groups. - Editing commands add (
a), insert (i), change (c), delete (d), print (p), transliterate (y) and quit (q). - Advanced commands move text between the pattern and hold spaces (
h,H,g,G,x) and branch with labels (:label,b,t,T) for loops.
The output model matters: with no -n, sed prints the pattern space at the end
of each cycle; with -n it prints nothing unless you ask.
Tips and examples
Delete blank lines and comment lines:
sed '/^$/d; /^#/d' config
Replace every tab with a comma across the whole file, in place with a backup:
sed -i.bak 's/\t/,/g' data.tsv
Print only lines 10 through 20:
sed -n '10,20p' file
Join all lines into one using the hold-space loop idiom:
sed ':a; N; $!ba; s/\n/ /g' file
Test changes by viewing output first, and only add -i once you are confident,
since in-place editing rewrites the original file.