sed Favorites

In-Place Edit with Backup

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

Delete Lines Matching Pattern

sed -i '/pattern/d' file.txt

Delete Empty Lines

sed -i '/^$/d' file.txt

Print Specific Line

sed -n '73p' /etc/ssh/sshd_config

Print Line Range

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

Replace on Specific Line

sed -i '73s/#GSSAPIAuthentication no/GSSAPIAuthentication yes/' /etc/ssh/sshd_config

Alternative Delimiters (Paths with /)

# Using # instead of /
sed 's#/old/path#/new/path#g' file.txt

# Using |
sed 's|http://|https://|g' file.txt

Insert Line Before Match

sed -i '/pattern/i\New line above' file.txt

Insert Line After Match

sed -i '/pattern/a\New line below' file.txt

Replace Only First Occurrence

sed -i '0,/old/{s/old/new/}' file.txt

Multiple Operations

sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt

Remove Leading Whitespace

sed 's/^[[:space:]]*//' file.txt

Remove Trailing Whitespace

sed 's/[[:space:]]*$//' file.txt

Comment Out Lines Matching Pattern

sed -i '/pattern/s/^/#/' file.txt

Uncomment Lines

sed -i 's/^#\(pattern\)/\1/' file.txt