I often find myself searching through a bunch of code using grep in order to pin down what I'm looking for. Sometimes I get a list of files a little longer than I hoped. At this point I want to perform a second grep, but only searching through the files returned by the first grep search. Is there a way to do this? I basically want to cross-reference two grep searches and only get back the files with both results contained within them.
1 Answer
grep -lZ "first string" * | xargs -0 grep -l "second string" First
grepwill return the files containingfirst string.Second
grepwill do the same forsecond string, but over the results from the firstgrep.The
-Zargument to grep and the-0argument to xargs work together to enable support for filenames that include spaces.
Edit - thanks to Ajedi32:
xargs lets you use the results from a command as the arguments to another.
From the xargs's Wikipedia article, xargs is a command on Unix and most Unix-like operating systems used to build and execute command lines from standard input.
- Awesome thank you. Can you enlighten me as to what
xargsis?ChevCast– ChevCast2014-08-04 17:26:46 +00:00Commented Aug 4, 2014 at 17:26 - 3@AlexFord - from the
xarg's Wikipedia article, xargs is a command on Unix and most Unix-like operating systems used to build and execute command lines from standard input.. In other words, it allows you to use the results from a command as the standard input to another. Try to use the same commands but withoutxargs, and you will see the problem (grep -l "first string" * | grep -l "second string")jimm-cl– jimm-cl2014-08-04 17:35:40 +00:00Commented Aug 4, 2014 at 17:35 - 1
- 2@jim "it allows you to use the results from a command as the standard input to another" No, that's what piping does. xargs lets you use the results from a command as the arguments to another.Ajedi32– Ajedi322014-08-04 20:04:47 +00:00Commented Aug 4, 2014 at 20:04
- 1@Ajedi32 - you are correct - my bad. Edited answer :-) Thanks!jimm-cl– jimm-cl2014-08-04 20:11:56 +00:00Commented Aug 4, 2014 at 20:11