Skip to content
Advertisement

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.

Advertisement

Answer

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.

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