How to grep the result of a grep?

Assuming none of the file names contain whitespace, single quote, double quote or backslash characters (or start with - with GNU grep), you can do:

grep -l word * | xargs grep word2

Xargs will run the second grep over each file from the first grep.

With GNU grep/xargs or compatible, you can make it more reliable with:

grep -lZ word ./* | xargs -r0 grep word2

Using -Z makes grep print the file names NUL-delimited so it can be used with xargs -0. The -r option to xargs avoids the second grep being run if the first grep doesn't find anything.

Tags:

Grep