text

sed

Stream editor that applies a small program to each line of input. Widely used for search-and-replace and inline file edits.

sed [OPTION]... {script} [FILE]...

Common flags

Flag Purpose
-i Edit files in place (accepts a backup suffix, e.g. -i.bak)
-e Add a script expression
-n Suppress default output; use with p to print explicitly
-E Use extended regular expressions
-r GNU alias for -E

Examples

sed 's/foo/bar/g' file.txt

Replace every foo with bar and print to stdout

sed -i 's|/old|/new|g' config.yml

In-place replacement using | as delimiter to avoid escaping slashes

sed -n '10,20p' log.txt

Print lines 10 through 20 only

sed -E 's/([0-9]+)/[\1]/g' data.txt

Wrap every number in brackets using extended regex

Gotcha

sed -i behavior differs between GNU and BSD (macOS) -- GNU accepts an empty suffix, BSD requires one; scripts targeting both should be explicit.

Related commands

← All Linux commands · Linux cheat sheet