Skip to content

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/' file

Replace the first occurrence of “old” with “new” in the file.

sed 's/old/new/g' file

Replace all occurrences of “old” with “new” in the file.

sed -n 'p' file

Print only the contents of the file.

sed 'd' file

Delete the contents of the file.

sed '2d' file

Delete the second line of the file.

sed '2,4d' file

Delete the second to fourth lines of the file.

sed '/pattern/d' file

Delete lines containing the pattern.

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

Perform replacement in the file and save changes.

Advanced Commands

sed -e 'command1' -e 'command2' file

Execute multiple commands.

sed -f script.sed file

Read commands from a script file.

sed 's/old/new/2' file

Replace only the second match.

sed 's/old/new/3g' file

Replace all matches starting from the third match.

sed 's/\(old\)/\U\1/g' file

Replace all “old” with uppercase.

sed 's/\(old\)/\L\1/g' file

Replace all “old” with lowercase.

sed 's/\(old\)/\E\1/g' file

Replace all “old” with uppercase and restore case after replacement.

sed 's/\(old\)/\e\1/g' file

Replace all “old” with lowercase and restore case after replacement.

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

Write the result of the replacement to a file.

sed -n 's/old/new/p' file

Print only the replaced lines.

sed -n '/pattern/p' file

Print only lines containing the pattern.

sed -n '1,5p' file

Print only lines one through five.

Step Selection Patterns

sed -n 'n~mp' file

Print 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 line n.