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)