Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find patterns across multiple lines using grep?

Tags:

regex

grep

I want to find files that have "abc" AND "efg" in that order, and those two strings are on different lines in that file. Eg: a file with content:

blah blah.. blah blah.. blah abc blah blah blah.. blah blah.. blah blah.. blah efg blah blah blah blah.. blah blah.. 

Should be matched.

like image 789
Saobi Avatar asked Apr 21 '10 19:04

Saobi


People also ask

How do I use grep to search for multiple patterns?

If you want to find exact matches for multiple patterns, pass the -w flag to the grep command. As you can see, the results are different. The first command shows all lines with the strings you used. The second command shows how to grep exact matches for multiple strings.

How do you grep multiple lines after a match?

Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!


1 Answers

Grep is an awkward tool for this operation.

pcregrep which is found in most of the modern Linux systems can be used as

pcregrep -M  'abc.*(\n|.)*efg' test.txt 

where -M, --multiline allow patterns to match more than one line

There is a newer pcre2grep also. Both are provided by the PCRE project.

pcre2grep is available for Mac OS X via Mac Ports as part of port pcre2:

% sudo port install pcre2  

and via Homebrew as:

% brew install pcre 

or for pcre2

% brew install pcre2 

pcre2grep is also available on Linux (Ubuntu 18.04+)

$ sudo apt install pcre2-utils # PCRE2 $ sudo apt install pcregrep    # Older PCRE 
like image 178
ring bearer Avatar answered Oct 12 '22 08:10

ring bearer