Display file content from the beginning up to a multi-line pattern

text processing

How can I display file content from the beginning up to some multi-line pattern without including the pattern itself?

For example, if I had a text file like this:

cat
dog
fox
cow
dove
bird
bunny
gnu
hen
dove
bird
buffalo

and if my pattern was this:

dove
bird
bunny

what I'd like to get would be:

cat
dog
fox
cow

My real file is huge so if there are multiple ways to achieve this, I'd prefer faster ways.

Also, I asked a similar question related to this just now, but it's different so please don't mark this as duplicate just because of that!

Best Answer

You could handle the input line-wise with sed and chain the multi-line pattern match:

/pat1/ { N; N; ...; /pat2\npat3\n.../q }

So in your example, that would be e.g.:

sed -n '/^dove$/ { N; N; /\nbird\nbunny$/q; }; p' infile

Output:

cat
dog
fox
cow
Related Question