Cheatsheet: sed

Last updated 2026-06-21

Substitution

Replace the first match on each line

sed 's/old/new/' file.txt

Replace every match on each line

sed 's/old/new/g' file.txt

Replace case-insensitively with GNU sed

sed 's/error/warning/I' file.txt

Use a different delimiter to avoid escaping slashes

sed 's#/usr/local#/opt/app#g' paths.txt

Edit a file in place with a backup

sed -i.bak 's/old/new/g' file.txt

Printing and deleting

Print only matching lines

sed -n '/ERROR/p' app.log

Print a specific line

sed -n '10p' file.txt

Print a range of lines

sed -n '10,20p' file.txt

Delete matching lines

sed '/^#/d' config.ini

Delete blank lines

sed '/^$/d' file.txt

Delete a range of lines

sed '5,10d' file.txt

Ranges and expressions

Substitute only within a line range

sed '10,20 s/foo/bar/g' file.txt

Substitute only between two matching markers

sed '/BEGIN/,/END/ s/enabled/disabled/g' file.txt

Run multiple sed expressions

sed -e 's/foo/bar/g' -e '/^$/d' file.txt

Use extended regular expressions

sed -E 's/[[:space:]]+/ /g' file.txt

Reuse capture groups in a replacement

sed -E 's/(.*), (.*)/\2, \1/' names.txt

Insert and append

Insert a line before a match

sed '/server_name/i\# Added by script' nginx.conf

Append a line after a match

sed '/server_name/a\include extra.conf;' nginx.conf

Change an entire matching line

sed '/^PORT=/c\PORT=8080' .env

Read from standard input in a pipeline

printf 'one two
' | sed 's/two/three/'

See also: