Oliver Williams
Oliver Williams

Reputation: 6344

linux grep match a subset of files from a previous match

I am needing pipe this result:

grep -R "extends Some_Critical_Class" *

to another grep:

grep "function init("

ie. "files that extend Some_Critical_Class that also have function init()"

If there is a way to do it in one operation in grep, that would be great, but I'd also like to see the how the piping is done to improve my programming in *nix (which is rudimentary right now). Thanks.

Upvotes: 1

Views: 222

Answers (2)

Ed Morton
Ed Morton

Reputation: 203684

Don't use grep (g/re/p) to find files, adding that functionality to GNU grep was just a bad idea since there's already a perfectly good tool to find files with an extremely obvious name.

You didn't say what your expected output was but maybe this does what you want:

find . -type f -exec \
awk '
    /extends Some_Critical_Class/ { x=1 }
    /function init\(/ { y=1 }
    END { if (x && y) print FILENAME }
' {} \;

The above will work on any Unix box, not just one with GNU tools, and can be trivially modified to add more regexps or strings to search for, various "and" and "or" combinations, etc.

Upvotes: 0

xhienne
xhienne

Reputation: 6144

To be clear, you want the list of files that contain both strings. Not only you need two greps for this, but you also need the -l (a.k.a. --files-with-matches) option.

Here is one way of doing this:

grep -F -R -l -Z "extends Some_Critical_Class" . \
| xargs -0 grep -F -l "function init("

We first obtain a (NUL-delimited) list of files that contain your first string, and then we use xargs to pass this list of files to the second grep.

Upvotes: 2

Related Questions