Sed Command Cheat Sheet
Sed is a stream editor used to perform basic text transformations and operations. It is one of the most powerful text processing tools in Unix systems.
Basic Commands
sed 's/old/new/' fileReplace the first occurrence of “old” with “new” in the file.
sed 's/old/new/g' fileReplace all occurrences of “old” with “new” in the file.
sed -n 'p' filePrint only the contents of the file.
sed 'd' fileDelete the contents of the file.
sed '2d' fileDelete the second line of the file.
sed '2,4d' fileDelete the second to fourth lines of the file.
sed '/pattern/d' fileDelete lines containing the pattern.
sed -i 's/old/new/g' filePerform replacement in the file and save changes.
Advanced Commands
sed -e 'command1' -e 'command2' fileExecute multiple commands.
sed -f script.sed fileRead commands from a script file.
sed 's/old/new/2' fileReplace only the second match.
sed 's/old/new/3g' fileReplace all matches starting from the third match.
sed 's/\(old\)/\U\1/g' fileReplace all “old” with uppercase.
sed 's/\(old\)/\L\1/g' fileReplace all “old” with lowercase.
sed 's/\(old\)/\E\1/g' fileReplace all “old” with uppercase and restore case after replacement.
sed 's/\(old\)/\e\1/g' fileReplace all “old” with lowercase and restore case after replacement.
sed 's/old/new/w output.txt' fileWrite the result of the replacement to a file.
sed -n 's/old/new/p' filePrint only the replaced lines.
sed -n '/pattern/p' filePrint only lines containing the pattern.
sed -n '1,5p' filePrint only lines one through five.
Step Selection Patterns
sed -n 'n~mp' filePrint every m-th line starting from line n.
Examples:
sed -n '1~2p' file: Print every other line (odd lines).sed -n '2~2p' file: Print every even line.sed -n '1~3p' file: Print every third line starting from the first.sed -n 'n~2p' file: This pattern continues for any starting linen.