Overview
Use sed to print transformed text without changing the original file. A substitution rule has the form s/pattern/replacement/. Preview the result before choosing an in-place edit.
Background
The name is short for stream editor: sed edits text as it flows from a file or pipe instead of opening it in an editor. A sed command, written by L. E. McMahon, appeared in Version 7 Unix, according to the FreeBSD and macOS manuals. Today the name covers separate programs: GNU sed, the sed that macOS ships, and the compact sed inside BusyBox. They agree on the substitution and printing examples below and differ on in-place editing, extensions, and regular-expression details.
Examples
Replace the first occurrence of old on each line:
sed 's/old/new/' notes.txt
Replace every occurrence on each line:
sed 's/old/new/g' notes.txt
Print only lines 2 through 4:
sed -n '2,4p' notes.txt
Delete the lines that match a pattern from the output:
sed '/second/d' notes.txt
Print only the lines that match a pattern:
sed -n '/third/p' notes.txt
Skip the first line, for example a header:
sed '1d' notes.txt
Print only the last line:
sed -n '$p' notes.txt
Apply two rules in order:
sed -e 's/old/new/' -e 's/second/2nd/' notes.txt
Use another delimiter when the pattern contains slashes:
echo '/usr/local/bin' | sed 's#/usr/local#/opt#'
Use an extended regular expression to replace runs of digits:
echo 'a1b22' | sed -E 's/[0-9]+/N/g'
Options
-n
Suppress automatic printing. Pair it with a rule such as p to explicitly print selected lines.
-e
Add an editing rule. Repeat -e to apply multiple rules in order.
-E
Use extended regular expressions, so +, ?, |, and () work without backslashes. GNU, macOS, and
BusyBox sed all accept -E.
Common mistakes
The substitution flag g changes every match on a line, not the number of files edited. Replacement text treats & specially: it expands to the matched text. Preview rules containing punctuation carefully.
Portability
In-place editing is not uniform across implementations. The examples below create backup files rather than discarding the original. Version-sensitive extensions are outside the common examples. The Common examples were executed on GNU sed 4.10, macOS sed, and BusyBox 1.37.0 (see the development guide for the exact check).
References
Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.