SED - delete words between two possible words

Hi all,

I want to make an script using sed that removes everything between 'begin' (including the line that has it) and 'end1' or 'end2', not removing this line.

Let me paste an 2 examples:

anything before
any string begin
few lines of content
end1
anything after
anything before
any string begin
few lines of content
end2
anything after

The desired output are:

anything before
end1
anything after

and

anything before
end2
anything after

I was trying something like sed '/begin/,/end1|end2/ d' <input >output but its very far away from what I want.

Thank you very much for helping

sed  '/begin/,/end[12]/{/end[12]/!d;}' infile
1 Like

Thank you, radoulov.

Let me ask one more question, because I can't find on Google neither regex tutorials: if it was foo/bar instead of end1/end2 ?

In that case you should use alternation (|) as in your original command:

sed  '/begin/,/foo\|bar/{/foo\|bar/!d;}' infile

It should be noted that only few sed implementations support alternation.

1 Like

That worked ! thank you my friend!