sed Cheatsheet - Linux Text Editing Reference

All essential sed commands organized by use case, with 37+ entries you can copy and run directly. Find the right command fast when you need it.

SysOps·37 commands·Last updated 2026-07-21
Back to SysOps

Substitute 8

sed 's/old/new/' file
Replace first match per line
sed 's/old/new/g' file
Replace all matches (global)
sed 's/old/new/2' file
Replace the 2nd match per line
sed 's/old/new/I' file
Case-insensitive match
sed -i 's/old/new/g' file
Edit the file in place
sed -i.bak 's/old/new/g' file
Edit and back up the original
sed 's/\/path\/old/path\/new/g' file
Escape slashes when replacing paths
sed 's|old|new|g' file
Use | as delimiter to avoid escaping slashes

Delete 7

sed '5d' file
Delete line 5
sed '5,10d' file
Delete lines 5-10
sed '/pattern/d' file
Delete matching lines
sed '/^$/d' file
Delete blank lines
sed '/^#/d' file
Delete comment lines
sed '$d' file
Delete the last line
sed '1d;$d' file
Delete the first and last lines

Insert & Append 5

sed '5i\new text' file
Insert before line 5
sed '5a\new text' file
Append after line 5
sed '/pattern/i\new text' file
Insert before matching lines
sed '/pattern/a\new text' file
Append after matching lines
sed '5i\line1\nline2' file
Insert multiple lines

Print 5

sed -n '5p' file
Print only line 5
sed -n '5,10p' file
Print only lines 5-10
sed -n '/pattern/p' file
Print only matching lines
sed -n '1p;$p' file
Print first and last lines
sed 's/old/new/p' file
Substitute and print changed lines

Regular Expression 7

sed 's/^prefix/new/' file
Match line start
sed 's/suffix$/new/' file
Match line end
sed 's/\<word\>/new/g' file
Match word boundary
sed 's/[0-9]/X/g' file
Match digits
sed 's/[^0-9]/X/g' file
Match non-digits
sed 's/\(pattern\)/\1/g' file
Capture group and backreference
sed -E 's/(old)/\1-new/g' file
Extended regex (-E or -r)

Multi-line 5

sed ':a;N;$!ba;s/\n//g' file
Delete all newlines
sed 'N;s/\n/ /'
Merge adjacent two lines
sed '/start/,/end/s/old/new/g' file
Substitute within a range
sed '/start/,/end/d' file
Delete lines within a range
sed '/start/,/end/p' file
Print lines within a range

Tips

  • Before editing in place with sed -i, back up first (-i.bak), or preview without -i.
  • sed uses BRE (basic regex) by default; +, ?, | must be escaped or enable ERE with -E.
  • On macOS, sed -i requires a backup suffix (e.g. -i ""); on Linux -i works directly.

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us