C.W.K.
Stream
Lesson 08 of 10 · published

sed — Stream Editor

~10 min · sed, shell, substitution

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

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:

  • -i in-place edit: BSD requires an extension argument (even if empty: sed -i '' 's/old/new/' file). GNU is just sed -i 's/old/new/' file.
  • Extended regex: BSD uses -E, GNU also accepts -r. -E works on both — use it.
  • Backslash interpretation: Subtle differences in how \n, \t are 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.

Code

sed examples·bash
# Basic substitution
sed 's/cat/dog/g' file.txt

# ERE syntax (recommended)
sed -E 's/(cat|dog)/animal/g' file.txt

# In-place edit (BSD/macOS — note empty extension)
sed -i '' 's/old/new/g' file.txt

# In-place edit (GNU/Linux)
sed -i 's/old/new/g' file.txt

# Capture groups (ERE)
echo 'order 1138' | sed -E 's/order ([0-9]+)/Order #\1/'
# Order #1138

# Reformat dates from ISO to MM/DD/YYYY
echo '2026-05-04' | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\2\/\3\/\1/'
# 05/04/2026

# Delete lines matching a pattern
sed '/^#/d' config.txt   # delete comment lines

# Print only lines matching a pattern
sed -n '/ERROR/p' log.txt

External links

Exercise

Take a CSV file with a date column in 'YYYY-MM-DD' format. Use sed to convert every date to 'MM/DD/YYYY' format, in place. Test on a copy first.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.