"sed" command examples
Remove every 2nd line:
sed 'n;d' input.txt
Remove 8th line:
sed 8d input.txt
Remove all empty lines:
sed /^$/d input.txt
Print each 10th line:
sed -n '0~10p' input.txt
Remove all lines from the beginning until the first empty line, inclusively:
sed 1,/^$/d input.txt
Print all lines containing "John" pattern:
sed -n /John/p input.txt
Replace first occurrence of "Windows" word with "Linux" word in each line:
sed s/Windows/Linux/ input.txt
Replace all occurrences of "Old" word with "New" word in each line:
sed s/Old/New/g input.txt
Remove all spaces in the end of each line:
sed s/ *$// input.txt
Replace all occurrences of leading zeros with a single zero symbol:
sed s/00*/0/g input.txt
Remove all lines containing "TRACE" word:
sed /TRACE/d input.txt
Remove all "ABC" words from each line:
sed s/GUI//g input.txt
Remove all lines before the first occurrence of "2014-05-09" and save results into the same file:
sed -i '0,/2014-05-09/d' gc-details.log
Replace multiple patterns using regular expressions and groups:
echo "I'm 20 years old and I live on Earth" | sed -r "s/(.*)20(.*)Earth/\1500\2Mars/"
I'm 500 years old and I live on Mars
Number each line with tab separator:
sed = input.txt | sed 'N;s/\n/\t/'
Number each non-empty line with space separator:
sed '/./=' input.txt | sed '/./N; s/\n/ /'
If a line end with "\" symbol then remove "\" and append next line:
sed -e :a -e '/\\$/N; s/\\\n//; ta' input.txt
If a line starts with "=" symbol then append the line to a previous one and replace "=" with space:
sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D' input.txt
Add an empty line after each line:
sed G input.txt
Add an empty line after each line, avoid multiple empty line:
sed '/^$/d;G' input.txt
Add two empty lines after each line:
sed 'G;G' input.txt
Add an empty line before each line containing "RED" word:
sed '/RED/{x;p;x;}' input.txt
Add an empty line after each line containing "GREEN" word:
sed '/GREEN/G' input.txt
Add empty lines before and after each line containing "GO" word:
sed '/GO/{x;p;x;G;}' input.txt