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

sed: Stream Editor

~15 min · sed, substitute, in-place

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The s/from/to/ engine

sed applies a small program to each line of input and prints the result. The most common command is s/pattern/replacement/ — substitute. Once you've used this, you'll never copy-paste-find-replace in a GUI editor again.

Substitution

  • sed 's/foo/bar/' — first occurrence per line.
  • sed 's/foo/bar/g' — every occurrence (global).
  • sed 's/foo/bar/I' — case-insensitive (GNU).
  • sed 's|/usr/local|/opt|g' — change delimiter when substituting paths (any single char works).
  • sed -E 's/(foo|bar)/[\1]/g' — extended regex with capture groups; \1 is the first captured group.

Other commands

  • sed '/pattern/d' — delete matching lines.
  • sed -n '5,10p' file — print only lines 5-10 (-n suppresses default output).
  • sed '$d' file — delete the last line.
  • sed '1i\\ header' file — insert text at line 1.

In-place editing

sed -i rewrites the file. BSD sed (macOS) requires an empty argument: sed -i '' 's/foo/bar/g' file. GNU sed: sed -i 's/foo/bar/g' file. The mismatch trips up everyone the first time. brew install gnu-sed + alias if you want consistency.

Sed vs awk vs perl

sed for line-by-line substitutions. awk for field-aware processing. perl -pe for serious regex (full PCRE with lookaheads). Each has its place; sed is the smallest and the most portable.

Code

Substitution patterns·bash
# Replace foo with bar globally, output to stdout
sed 's/foo/bar/g' file.txt
# In place — macOS BSD
sed -i '' 's/foo/bar/g' file.txt
# In place — GNU (linux or brew install gnu-sed)
sed -i 's/foo/bar/g' file.txt
# Slash in pattern? change delimiter
sed 's|/usr/local|/opt/homebrew|g' install.sh
Delete + extract·bash
# Drop blank lines
sed '/^$/d' file
# Print only lines 100-110
sed -n '100,110p' big.log
# Strip trailing whitespace
sed -E 's/[[:space:]]+$//' file

External links

Exercise

Make a copy of ~/.zshrc to /tmp/zshrc.bak. Try sed -n '1,10p' /tmp/zshrc.bak. Then sed 's/^export/EXPORT/' /tmp/zshrc.bak | head. Finally, in-place: sed -i '' 's/EXPORT/export/' /tmp/zshrc.bak (mac) or sed -i 's/EXPORT/export/' /tmp/zshrc.bak (linux).

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.