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/'

Bibliography