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
Core Options
-nSilent mode. Suppresses automatic printing of pattern space. Use 'p' command to print lines explicitly.
-iIn-place edit. Modifies the file directly. Use with caution (or provide a backup extension like -i.bak).
-e scriptAdd valid script commands to be executed.
-EUse 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.txtGlobal String Substitution
Replaces ALL occurrences of 'foo' with 'bar' in the file (using the /g flag).
sed 's/foo/bar/g' input.txtDelete Specific Lines
Deletes the first line of the file.
sed '1d' input.txtDelete Range of Lines
Deletes from line 5 to line 10.
sed '5,10d' input.txtPrint Only Matching Lines
Uses -n (silent) and p (print) to behave like grep, printing only lines containing 'error'.
sed -n '/error/p' logfile.logMultiple Commands
Delete line 1 AND replace 'foo' with 'bar'.
sed -e '1d' -e 's/foo/bar/g' input.txtInsert Line Before a Match
Inserts 'Start of Section' before every line containing 'Chapter'.
sed '/Chapter/i Start of Section' book.txt