[Solved-6 Solutions] How to find patterns across multiple lines using grep - Linux Tutorial



Problem :

How to find patterns across multiple lines using grep ?

Solution 1:

You can use grep. incase you are not keen in the sequence of the pattern.

grep -l "pattern1" filepattern*.* | xargs grep "pattern2"

Example:

grep -l "vector" *.cpp | xargs grep "map"

grep -l will find all the files which matches the first pattern, and xargs will grep for the second pattern.

Solution 2:

In the modern Linux systems using as

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

pcre2grep is available for Mac OS X

% sudo port install pcre2 

and via Homebrew as:

% brew install pcre

Solution 3:

It is simple to make:

sed -e '/abc/,/efg/!d' [file-with-content]

Solution 4:

At the same line to display as 'abc' and 'efg' can be :

grep -zl 'abc.*efg' <your list of files>

At different lines to display as 'abc' and 'efg' must be:

grep -Pzl '(?s)abc.*\n.*efg' <list of files>

-z Set of lines to terminated as zero

-l print each input file as name from the output to be printed.

(?s) activate PCRE_DOTALL, which means that '.' finds any character or newline

Solution 5:

Using p to print as simple:

sed -n '/abc/,/efg/p' file

Solution 6:

Using Perl.

perl -ne 'if (/abc/) { $abc = 1; next }; print "Found in $ARGV\n" if ($abc && /efg/); }' yourfilename.txt

Single regular expression an involves taking the entire contents of the file into a single string.

perl -e '@lines = <>; $content = join("", @lines); print "Found in $ARGV\n" if ($content =~ /abc.*efg/s);' yourfilename.txt


Related Searches to - linux - linux tutorial - How to find patterns across multiple lines using grep ?