Sed Command Cheat Sheet

Basic Usage

sed 's/old/new/' filename

Replace the first occurrence of "old" with "new" in each line.

sed 's/old/new/g' filename

Replace all occurrences of "old" with "new" in each line.

sed -i 's/old/new/g' filename

Modify the file in place, replacing all occurrences of "old" with "new".

Common Options

sed -n '3p' filename - Print only the third line of the file.

sed -n '2,4p' filename - Print lines 2 through 4.

sed '3d' filename - Delete the third line.

sed '2,4d' filename - Delete lines 2 through 4.

sed '$d' filename - Delete the last line.

Advanced Usage

sed 's/old/new/2' filename - Replace only the second occurrence of "old" in each line.

sed '1,3s/old/new/g' filename - Replace "old" with "new" only in lines 1 through 3.

sed '/pattern/d' filename - Delete lines that contain "pattern".

sed 's/\bword\b/replacement/g' filename - Replace whole word matches only.

sed 's/\(old\)/\U\1/g' filename - Convert "old" to uppercase.

sed 's/\(old\)/\L\1/g' filename - Convert "old" to lowercase.