hadis hadis - 10 months ago 36
Linux Question

How can I search for multiple patterns recursively in linux?

I am trying to find files that include either of the following two patterns:

select AND into
select AND INTO

By AND, I mean a logical end. I am using the following command:

grep -r 'INTO\|SELECT' .

to check if a file has INTO AND SELECT, but this returns the string if either one exists, but I need both.

cxw cxw

If the patterns have to occur on the same line, you can use

grep -r '\(INTO.*SELECT\)\|\(SELECT.*INTO\)' .

The two alternatives are to cover either order. If the two patterns can occur on separate lines, try this:

grep -r -Z -l 'INTO' . | xargs -0 grep 'SELECT'

The first grep will print the names (-l) of the files that have INTO. -Z and xargs -0 work together to pass those names to a second grep, which looks for SELECT.

Note thanks to @ghoti: for grep versions other than GNU, try --null instead of -Z.