The classic substitution tool
sed stands for "stream editor." Its bread and butter is sed 's/pattern/replacement/flags' — apply a regex substitution to each line of input.
Basic syntax
sed 's/pattern/replacement/g' file.txt
sed -E 's/pattern/replacement/g' file.txt # ERE syntax (recommended)
echo 'hello' | sed 's/h/H/' # piped input
Common flags:
g— replace all on each line (default is first per line)i— case-insensitive (GNU sed)2,3... — replace only the Nth occurrence per line
BSD vs GNU sed
macOS comes with BSD sed; Linux with GNU sed. They differ in important ways:
-iin-place edit: BSD requires an extension argument (even if empty:sed -i '' 's/old/new/' file). GNU is justsed -i 's/old/new/' file.- Extended regex: BSD uses
-E, GNU also accepts-r.-Eworks on both — use it. - Backslash interpretation: Subtle differences in how
\n,\tare handled in replacements.
For cross-platform scripts, use gsed (GNU sed installed via brew install gnu-sed) or write Python instead.
Capture groups
In sed BRE (default), groups need backslash escaping: \(...\). With -E for ERE, plain parens work.
Reference captures with \1, \2 in the replacement.