sed Quick Start
sed and awk are powerful tools for text stream processing. This article provides a quick-start reference for the sed command.
- Ryan
- 2 min read

sed and awk are powerful tools for text stream processing. This article provides a quick-start reference for the sed command:
Delete Command
Delete the Nth line
sed 3d abc.txt
This command deletes the third line.
Delete every other line
sed '1~2d' abc.txt
sed '2~2d' abc.txt
The first command deletes odd-numbered lines, and the second deletes even-numbered lines.
Delete lines from N to M
sed '5,11d' abc.txt
Deletes lines 5 through 11.
Delete the last line
sed '$d' abc.txt
Delete lines matching a pattern
sed /unix/d abc.txt
This command deletes all lines containing the unix keyword.
Delete a matching line and the N lines after it
sed '/unix/,+3d' abc.txt
This command deletes the line containing the unix keyword plus the next 3 lines.
Delete from a matching line to the end of the file
sed '/unix/,$d' abc.txt
This command deletes the line containing the unix keyword and all lines after it to the end of the file.
Delete all blank lines
sed '/^$/d' abc.txt
This command deletes all blank lines in abc.txt.
Delete all comment lines
Here we assume lines are commented with the # symbol.
sed '/#.*/d' abc.txt
This command deletes all comment lines.
Substitution Command
s stands for substitution, and / is the delimiter.
Single substitution
sed 's/old/new/'
This command replaces the first occurrence of ‘old’ with ’new’.
Global substitution
sed 's/old/new/g'
This command replaces all occurrences of ‘old’ with ’new’.
Substitute a piped data stream
echo "old" | sed 's/old/new/'
This command outputs ’new'.
Substitute a file’s data stream
sed 's/old/new/' filename
This command replaces ‘old’ with ’new’ and prints the result to the console.
Substitute a file’s data stream and save it
sed -i 's/old/new/' filename
The -i option replaces ‘old’ and saves the result back to the file.