user1472747
user1472747

Reputation: 567

Search pattern over multiple lines?

I'm trying to find a pattern of 3 words over any lines with anything in between them. Currently, I'm using pcregrep this way (-M is for multiline):

sep=$( echo ".*\n.*" )

find . -name "$FILE" 2>null | xargs pcregrep -M "string1($sep)string2($sep)string3" >> $grep_out

And I get this result:

./testing/test.txt:   let prep = "select string1, dog from cat",
              " where string2 = 1",
              " and string3 = ?",

Which is great. However, I want this pattern to find these 3 strings over several newlines - not just consecutively. For example, I would want this result to be found:

./testing/test.txt:   let prep = "select string1, dog from cat",
              " where apple = 1",
              " and string2 = 2",
              " and grass = 8",
              " and string3 = ?",

It makes sense that my pattern does not match the above result right now, because it is only looking for a single newline. So, I would think that changing my code to be this way would fix this (changing the $sep variable and adding asterisk to search pattern):

sep=$( echo ".|\n" )

find . -name "$FILE" 2>null | xargs pcregrep -M "string1($sep)*string2($sep)*string3" >> $grep_out

But this yields no results, now. Putting the asterisks inside of the parenthesis also yield no results. So I'm still looking for a pattern which will allow 0 or more of any character, including newlines, in between my 3 strings.

Upvotes: 0

Views: 113

Answers (1)

user2987828
user2987828

Reputation: 1137

find . -name "$FILE" 2>/dev/null -execdir \
sh -c "grep -aA999999 string1 '"{}"' | grep -aA999999 string2 | grep -q string3" \
';' -print

which is limited to 999999 lines between string1, string2 and string3.

Do not put spaces after the \.

Upvotes: 2

Related Questions