How can I search for a multiline pattern in a file?

command-line, find, grep, linux, pcregrep

Solution

So I discovered pcregrep which stands for Perl Compatible Regular Expressions GREP.

the -M option makes it possible to search for patterns that span line boundaries.

For example, you need to find files where the '_name' variable is followed on the next line by the '_description' variable:

find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'

Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...

Problem

I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep: ``` find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN' ``` But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.

Original source

Related problems