Skip to content
Advertisement

How can I recursively search for multiple patterns on linux?

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

select AND into
SELECT AND INTO
select AND INTO
SELECT AND into

By AND, I mean a logical and. 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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement