Grep multiline pattern

grepnewlinesregex

How do I search for a phrase over multiple lines? E.g. Lets have the phrase "my ice tea" then it may be wrapped in text files:

as js skdfh dfh djh sf my
ice tea.

grep will not match since there is a newline in between. How do I match those? Another multiline pattern would be pattern1_\n_pattern2

I know the easiest way I do ATM is just grep for one part e.g. just ice with -A2 -B2 flag and then in that output againg for e.g. tea. But this is very tedious. So I am interessted on how do you would solve this.

Best Answer

You could install pcregrep (available in most distro repositories) - which is grep using the pcre library, which does "Perl Compatible Regular Expressions". It has a command line option -M which allows you to do multiline searches - from the man page:

"The output for any one match may consist of more than one line."

So you could do

pcregrep -M 'my\s+ice\s+tea' filename

The \s is whitespace, which will match \n and \r in multiline mode, in addition to the normal whitespace characters. You can also match the newline character directly, so you could do

pcregrep -M 'pattern1_\n_pattern2' filename
Related Question