Skip to main content

sed

Stream editor for filtering and transforming text.

Basics

  • Substitute first match per line
sed 's/foo/bar/' file
  • Substitute all matches per line
sed 's/foo/bar/g' file
  • In-place edit (GNU sed)
sed -i 's/old/new/g' file
# with backup
sed -i.bak 's/old/new/g' file

Regex and delimiters

  • Use different delimiter to avoid escaping slashes
sed 's#https://old#https://new#g' file
  • Extended regex
sed -E 's/(foo|bar)[0-9]+/X/g' file

Addressing lines

  • Only lines matching pattern
sed '/ERROR/s/foo/bar/g' file
  • Line ranges
sed '10,20d' file         # delete lines 10-20
sed '1,5p' file -n # print lines 1-5

Insert/append

  • Insert before match
sed '/pattern/i\\inserted line' file
  • Append after match
sed '/pattern/a\\appended line' file

Capture groups

  • Reorder CSV columns 2 and 3
sed -E 's/^([^,]+),([^,]+),([^,]+)/\1,\3,\2/' file.csv

Delete/keep

  • Delete blank lines
sed '/^$/d' file
  • Keep only matching lines (print)
sed -n '/SUCCESS/p' file

Tips

  • Combine multiple -e scripts: sed -E -e 's/a/b/' -e '/x/d'
  • For complex edits, prefer awk or a small script.