Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep or ripgrep: How to find only files that match multiple patterns (not only on the same line)?

Tags:

grep

ripgrep

I'm searching for a fast method to find all files in a folder which contain 2 or more patterns

grep -l -e foo -e bar ./* or rg -l -e foo -e bar

show all files containing 'foo' AND 'bar' in the same line or 'foo' OR 'bar' in different lines but I want only files that have at a minimum one 'foo' match AND one 'bar' match in different lines. Files which only have 'foo' matches or only 'bar' matches shall be filtered out.

I know I could chain the grep calls but this will be too slow.

like image 321
maikelmeyers Avatar asked Nov 26 '19 14:11

maikelmeyers


1 Answers

$ cat f1
afoot
2bar
$ cat f2
foo bar
$ cat f3
foot
$ cat f4
bar
$ cat f5
barred
123
foo3

$ rg -Ul '(?s)foo.*?\n.*?bar|bar.*?\n.*?foo'
f5
f1

You can use -U option to match across lines. The s flag will enable . to match newlines as well. Since you want the matches to be across different lines, you need to match a newline character in between the search terms as well.

like image 114
Sundeep Avatar answered Dec 13 '22 08:12

Sundeep