Using sed to delete everything between two words?

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.


I would use

sed 'N;N;s/ONE.*\n.*TWO/ONE TWO/' file

Note the two N operations to join three lines together to allow the s opertation to work.

(this also keeps close to your original example).

Tags:

Sed