sed

Stream EDitor. A powerful utility that parses and transforms text, line by line. It is indispensable for automated file editing and complex text processing pipelines.

Synopsis

sed [options] 'command' file(s)

Core Options

-n

Silent mode. Suppresses automatic printing of pattern space. Use 'p' command to print lines explicitly.

-i

In-place edit. Modifies the file directly. Use with caution (or provide a backup extension like -i.bak).

-e script

Add valid script commands to be executed.

-E

Use extended regular expressions (ERE) instead of basic regular expressions (BRE).

Usage Examples

String Substitution (First Occurrence)

Replaces the first occurrence of 'foo' with 'bar' in each line.

sed 's/foo/bar/' input.txt

Global String Substitution

Replaces ALL occurrences of 'foo' with 'bar' in the file (using the /g flag).

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

Delete Specific Lines

Deletes the first line of the file.

sed '1d' input.txt

Delete Range of Lines

Deletes from line 5 to line 10.

sed '5,10d' input.txt

Print Only Matching Lines

Uses -n (silent) and p (print) to behave like grep, printing only lines containing 'error'.

sed -n '/error/p' logfile.log

Multiple Commands

Delete line 1 AND replace 'foo' with 'bar'.

sed -e '1d' -e 's/foo/bar/g' input.txt

Insert Line Before a Match

Inserts 'Start of Section' before every line containing 'Chapter'.

sed '/Chapter/i Start of Section' book.txt
Built for builders.