Sed – How to Delete Everything Between Two Words

sed

This doesn't seem to work

The next example would delete everything between "ONE" and "TWO:" 

#!/bin/sh
sed '
/ONE/ {
# append a line
    N
# search for TWO on the second line 
    /\n.*TWO/ {
# found it - now edit making one line
        s/ONE.*\n.*TWO/ONE TWO/
    }
}' file

i was expecting to delete everything between ONE and TWO.i tried with file
where file contains.

[user5@mailserver ~]$ cat file
ONE
hello
TWO

but the output come like

[user5@mailserver ~]$ ./test
ONE
hello
TWO

I was expecting ONE TWO
I am trying to make it correct but not able to do.

Best Answer

This will do the job

sed '/^ONE/,/TWO/{/^ONE/!{/TWO/!d}}' file

/^ONE/,/TWO/ Look at the first line starting with ONE up to TWO

{/^ONE/! do the following if my line does not start with ONE

{/TWO/!d}} do the following if my line does not start with TWO and delete

To summerize the above:

Find everything that starts with ONE up to TWO. Another check is ran which means, find everything that don't match 'ONEandTWO` and delete the rest.

Related Question