sed
Examples
Delete blank lines
sed -i '/^$/d' file.txt
Delete a line matching search only if next line matches a different search
The following example removes lines containing the search term /ONE/ but only if they are followed by a line matching the search term /TWO/.
test.txt
ONE
TWO
THREE
TWO
ONE
THREE
ONE
TWO
test.sh
#!/bin/sh
sed '
/ONE/ {
# append a line
N
# if TWO found, delete the first line
/\n.*TWO/ D
}' test.txt
Output of: sh test.sh
TWO
THREE
TWO
ONE
THREE
TWO
Delete lines containing duplicate search term
The following example only outputs a line that matches the search term /Plan/ if the line following it does not match the search term /Plan/. Lines that do not match the search term /Plan/ are unaffected and are output as found.
test2.txt
Plan NO
Plan YES
1111
Plan YES
2222
Plan NO
Plan NO
Plan NO
Plan YES
3333
Plan NO
test2.sh
#!/bin/sh
sed '
/Plan/ {
# append a line
N
# if TWO found, delete the first line
/\n.*Plan/ D
}' test2.txt
Output of: sh test2.sh
Plan YES
1111
Plan YES
2222
Plan YES
3333
Plan NO
FizzBuzz
seq 100 | sed '0~3s/.*/Fizz/;0~5s/[0-9]*$/Buzz/'
Use of the tilde specifies a starting line number and an increment (i.e. 0~3 means every third line, 0~5 means every fifth line).
On every third line we are replacing everything already there (i.e. our number) with the word Fizz. On every fifth line we are only replacing anything after a numeric value (in case there is a Fizz there already) with the word Buzz.
This assumes that we are starting our count at 1 and that the line number therefore matches the actual number. i.e. seq 2 100... will not work