Tools › Cheat sheets › Linux & Shell › sed
✂️

sed cheat sheet

sed edits text line by line. The most common command is s/old/new/. These examples use GNU sed (Linux); on macOS/BSD, use -i '' instead of -i.

Click any command to copy it.

Substitute

CommandWhat it does
sed 's/old/new/' fileReplace the first match on each line.
sed 's/old/new/g' fileReplace all matches on each line.
sed 's/old/new/I' fileCase-insensitive replace (GNU).
sed 's|/usr/local|/opt|g' fileUse another delimiter when the text contains slashes.
sed -E 's/([a-z]+) ([a-z]+)/\2 \1/' fileExtended regex with groups; swap two words.
sed 's/foo/[&]/g' file& stands for the whole match.
sed -e 's/a/b/' -e 's/c/d/' fileApply several edits in one pass.

Print and delete lines

CommandWhat it does
sed -n '5p' filePrint only line 5.
sed -n '10,20p' filePrint lines 10 to 20.
sed '1d' fileDelete the first line.
sed '$d' fileDelete the last line.
sed '/pattern/d' fileDelete lines matching a pattern.
sed '/^$/d' fileDelete empty lines.
sed '/^#/d' fileDelete comment lines.
sed -n '/start/,/end/p' filePrint the lines between two patterns.
sed -n '/pattern/p' filePrint only lines matching a pattern (like grep).

Insert and modify

CommandWhat it does
sed '2i\New line' fileInsert a line before line 2 (GNU).
sed '/pattern/a\Appended line' fileAppend a line after each match (GNU).
sed 's/^/> /' fileAdd a prefix to every line.
sed 's/$/;/' fileAdd a suffix to every line.
sed 's/[ \t]*$//' fileRemove trailing whitespace.
sed 'y/abc/xyz/' fileTransliterate characters (a to x, b to y, c to z).
sed '3s/old/new/' fileApply a substitution only on line 3.

Edit files in place

CommandWhat it does
sed -i 's/old/new/g' fileDestructive: Edit the file directly with no undo. Preview first without -i.
sed -i.bak 's/old/new/g' fileEdit in place and keep a backup named file.bak.
sed -i 's/old/new/g' *.confDestructive: Edit every matching file in place.
sed -i '/pattern/d' fileDestructive: Delete matching lines from the file permanently.
sed -i '1i #!/bin/bash' fileInsert a line at the top of the file (GNU).

Frequently asked questions

Why does sed -i fail on macOS?

BSD sed requires a backup suffix argument. Use sed -i '' 's/a/b/' file, or install GNU sed (gsed).

How do I replace text containing slashes?

Choose a different delimiter, for example sed 's|/old/path|/new/path|g'.

More Linux & Shell cheat sheets

🐚 Bash🔎 grep🔍 find🧮 awk📦 tar📝 Vim🪟 tmux🔐 chmod permissionsAll Linux & Shell cheat sheets →
Copied to clipboard