Sed Cheat Sheet

Substitute

Replace “foo” with “bar” all instances.

sed 's/foo/bar/g'

Replace “foo” with “bar” but only the 1st instance of a line

sed 's/foo/bar/'

Replace “foo” with “bar” but only the 4th instance of a line

sed 's/foo/bar/4'

Replace “foo” with “bar” only for lines which contain “baz”

sed '/baz/s/foo/bar/g'

Substitute on the fly

substitute all instances of apple with lemon

sed -i 's/apple/lemon/g' filename

Insert

Insert character (regex) at the beginning of each line

sed 's/^/regex/'

Insert character (regex) at the end of each line

sed 's/$/regex/'

Insert line / character (regex) above match

cat file |sed 's/.*match.*/txtabove\n&/'

Insert line / character (regex) below match

cat file |sed 's/.*match.*/&\ntxtbelow/'

Delete

Delete empty lines.

sed '/^$/d'

Delete first character of each line.

sed 's/^.//'

Delete first character (regex) of each line

sed 's/^regex//'

Delete last character on each line.

sed s'/.$//'

Delete last character (regex) on each line

sed 's/regex$//'

Delete the first line of a file

sed '1d'

Delete the first 10 lines of a file

sed '1,10d'

Delete the last line of a file

sed '$d'

Delete leading whitespace from the beginning of each line1)
1) Note: replace \t with TAB if used from the command line

sed 's/^[ \t]*//'

Delete trailing whitespace, from the end of each line1)
1) Note: replace \t with TAB if used from the command line

sed 's/[ \t]*$//'

Delete both leading and trailing whitespace from each line1)
1) Note: replace \t with TAB if used from the command line

sed 's/^[ \t]*//;s/[ \t]*$//'

Misc

Join pairs of lines side-by-side like “paste”

sed '$!N;s/\n/ /'

If a line ends with a backslash, append the next line to it

sed -e :a -e '/\\$/N; s/\\\n//; ta'

Remove ^M from file. The ^M character can be input using CTRL+V + CTRL+M</sup>

sed 's/^M//g'