On this page 12 sections
How sed works
sed is a stream editor. It reads text line by line, applies editing instructions and writes the result to standard output. By default it does not modify the original file.
sed 's/http/https/' urls.txtSubstitute text
The s command replaces text. Without additional flags only the first occurrence on each line is replaced.
sed 's/dev/prod/' config.txtsed 's/dev/prod/g' config.txtCase-insensitive replacement
GNU sed supports the I flag for case-insensitive matching.
sed 's/error/warning/gI' application.logUse alternative delimiters
The slash character is conventional but not mandatory. Different delimiters make replacements involving filesystem paths or URLs much easier to read.
sed 's#http://sam0x.me#https://sam0x.me#g' config.txtModify a file in place
-i writes changes back to the file. Creating a backup suffix before editing important configurations is safer.
sed -i 's/dev/prod/g' config.txtsed -i.bak 's/dev/prod/g' config.txtDelete lines
The d command removes matching lines from the output.
sed '/^$/d' file.txtsed '/^[[:space:]]*#/d' config.txtsed '/^[[:space:]]*#/d; /^[[:space:]]*$/d' config.txtPrint selected lines
-n disables automatic output. The p command can then print only the lines or ranges you explicitly select.
sed -n '10p' file.txtsed -n '10,20p' file.txtsed -n '/ERROR/p' application.logWork with ranges
sed can apply commands only to a numeric range or between two matching patterns.
sed '1,5d' file.txtsed -n '/BEGIN CONFIG/,/END CONFIG/p' file.txtCapture groups
Extended regular expressions combined with capture groups make it possible to extract and rearrange parts of a line.
echo 'user=sam0x' | sed -E 's/^user=(.*)$/\1/'echo 'sam0x:admin' | sed -E 's/^([^:]+):([^:]+)$/\2:\1/'Remove leading and trailing whitespace
Whitespace cleanup is a common sed use case when normalising command or configuration output.
sed 's/^[[:space:]]*//' file.txtsed 's/[[:space:]]*$//' file.txtAppend and insert lines
a appends text after a selected line while i inserts text before it.
sed '/server_name/a\ # managed by sam0x' nginx.confsed '/server_name/i\ # virtual host' nginx.confMultiple sed expressions
-e allows several transformations to be applied in sequence.
sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' config.txt