cheat-sheets

SED Cheat-Sheet

sed (“stream editor”) is a Linux and Unix utility that parses and transforms text using a compact programming language. See also Grep and Awk.

On macOS (BSD sed) use sed -i '' instead of sed -i.

Substitution #

COMMANDDESCRIPTION
sed 's/old/new/' fileReplace first match on each line
sed 's/old/new/g' fileReplace all matches on each line
sed -i 's/old/new/g' fileEdit the file in place
sed -i.bak 's/old/new/g' fileEdit in place and keep a .bak backup
sed 's/old/new/2' fileReplace only the 2nd match on each line
sed 's/old/new/gI' fileCase-insensitive replace (GNU sed)
sed 's|/usr/local|/opt|g' fileUse another delimiter when the pattern contains /
sed -E 's/([a-z]+)@([a-z]+)/\2 at \1/' fileExtended regex with capture groups
sed 's/.*/\U&/' fileUppercase each line (GNU sed)
sed 's/[ \t]*$//' fileStrip trailing whitespace
COMMANDDESCRIPTION
sed -n '5p' filePrint line 5
sed -n '5,10p' filePrint lines 5 to 10
sed -n '/start/,/end/p' filePrint between two patterns
sed -n '$p' filePrint the last line
sed '5d' fileDelete line 5
sed '/^#/d' fileDelete comment lines
sed '/^$/d' fileDelete empty lines
sed '1d;$d' fileDelete first and last lines
sed -n '/error/{p;q}' filePrint first match then quit

Insert and Append #

COMMANDDESCRIPTION
sed '3i\New line' fileInsert before line 3
sed '3a\New line' fileAppend after line 3
sed '/pattern/a\New line' fileAppend after matching lines
sed '1i\#!/bin/bash' fileAdd a line at the top
sed '$a\New last line' fileAdd a line at the end
sed 's/^/ /' fileIndent every line by 4 spaces
sed '/pattern/c\Replacement line' fileReplace the whole matching line

Multiple Commands #

COMMANDDESCRIPTION
sed -e 's/a/b/' -e 's/c/d/' fileChain expressions
sed 's/a/b/;s/c/d/' fileSame, with ;
sed -f script.sed fileRead commands from a file
sed = file | sed 'N;s/\n/\t/'Number lines
Search all sheets

Tip: / or Ctrl/Cmd+K to open, Esc to close.