In-place edits

GNU sed

sed -i 's/foo/bar/g' file.txt

Input

foo bar
foo baz

Output

bar bar
bar baz

Edits a file without a backup. g replaces every match on each line. See GNU sed.

Keep a backup

sed -i.bak 's/foo/bar/g' file.txt

Keeps a backup before editing. Writes file.txt.bak; the suffix follows -i with no space. See GNU sed.

macOS and BSD

sed -i '' 's/foo/bar/g' file.txt

Handles BSD sed's backup argument. BSD sed requires an explicit suffix; an empty string means no backup. See BSD sed.

Extended regex

sed -E 's/(foo|bar)/baz/g' file.txt

Input

foo bar
bazqux

Output

baz baz
bazqux

Enables extended regular expressions. -E supports | and groups. See GNU sed.

0 Comments for this cheatsheet. Write yours!