SED Tutorial

20th of February, 2021
linux, ops

sed is a great tool for working with text. Here is a quick primer.
by Tom Rothe

sed Tutorial

I always asked myself how sed really worked. I have used it on so many occasions, but never quite understood what I had copied from stackoverflow. It was time to understand it a little better:

Cheat sheet

The general structure of a command is:

sed '[command]'
# a [command] consists of two parts `[address][function]`.
Usage  
cmd -> sed -> file echo 'xxx' | sed '' > output.txt
cmd -> sed -> cmd echo 'xxx' | sed '' | wc
file -> sed -> cmd sed '' input.txt | wc
file -> sed -> same file sed -i '' file.txt
Options  
echo abc | sed '' Read from stdin, do no command ('')
sed -i '' file.txt Replace file in-place (requires file to be given)
sed -i.bak '' file.txt Replace file in-place with backup
sed -e '' -e '' Run multiple commands
sed -n '' Disable automatic printing; prints only lines affected the command
Addresses  
sed 'p' Apply command to all lines (command is p for print)
sed '2p' Apply to line 2
sed '2,4p' Apply for each line between 2 and 4 (inclusive)
sed '3~2p' Apply to every other line starting at the 3rd line
sed '$p' Apply to last line
sed '/match/p' Apply only matching lines
sed '/match/!p' Apply to lines that do not match
Functions  
sed -n 'p' Print each line (-n suppresses default printing)
sed 'a Text' Append text after each line
sed 'i Text' Insert text before each line
sed 'd' 3rd each line
sed 's/old/new/' replace first occurrence of regular expression with new value
sed 's/old/new/g' replace all occurrences (non-overlapping)
sed 's/old/new/i' replace case-insensitive
sed 's/old\(.+\)/new\1/' replace with matched group (brackets must be escaped)
Examples  
sed -n '/match/p' Print matched lines
sed -n '/match/!p' Print lines that do not match
sed '2i text' Prepend text before line 2
sed '$a text' Append line at the end
sed '3d' Delete 3rd line
sed '/match/i text' Insert text before each matching line
sed -n '/match/!d' Delete lines that do not match
sed ‘/^prefix/d’ Delete lines starting with prefix.
sed '3 s/old/new/' Only replace on the 3rd line
sed '/prefix/s/old/new/' Only replace if the line starts with prefix
sed ‘s/#.*$//’ Remove comments
sed ‘s/\s*$/a/’ Remove trailing whitespace
sed ‘/^$/d’ Remove empty lines

Show Notes