The sed command

stream editor for filtering and transforming text 17 examples from the lessons of the IVski Linux Playground — try them in the terminal next to them.

Examples

sed 's/old/new/' file.txt

Replace first occurrence per line

sed 's/old/new/g' file.txt

Replace all occurrences (global)

sed 's/old/new/i' file.txt

Case-insensitive

sed 's/old/new/2' file.txt

Replace 2nd occurrence only

sed -i 's/old/new/g' file.txt

Modify file directly

sed -i.bak 's/old/new/g' file.txt

Modify and create .bak backup

sed '/pattern/d' file.txt

Delete lines matching pattern

sed '3d' file.txt

Delete line 3

sed '2,5d' file.txt

Delete lines 2-5

sed '/^#/d' file.txt

Delete comment lines

sed '/^$/d' file.txt

Delete empty lines

sed -n '5p' file.txt

Print line 5

sed -n '2,8p' file.txt

Print lines 2-8

sed -n '/pattern/p' file.txt

Print matching lines

sed -i 's/http:/https:/g' config.txt
sed 's/^[ \t]*//' file.txt
sudo sed -i 's/sk_live_[A-Za-z0-9]*/sk_live_REDACTED/g' FILE

Replace in place (the logs belong to root)

Lessons that use sed