How to edit text with sed in Linux

· Category: Linux

Short answer

sed is a stream editor that modifies text in a pipeline or file using simple commands.

Steps

  1. Replace text:
sed 's/foo/bar/g' file.txt
  1. Edit in place:
sed -i 's/foo/bar/g' file.txt
  1. Delete lines:
sed '/pattern/d' file.txt
  1. Replace on specific lines:
sed '3s/foo/bar/' file.txt

Tips

  • sed -i.bak creates a backup before editing.
  • Use extended regex with sed -E.
  • Escape delimiters if your pattern contains slashes: sed 's|/usr/local|/opt|g'.

Common issues

  • sed -i behavior differs between GNU and BSD/macOS versions.
  • Global replacement requires the g flag; otherwise only the first match per line is replaced.