Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 9 down vote accepted
grep -lZ "first string" * | xargs -0 grep -l "second string"
  • First grep will return the files containing first string.

  • Second grep will do the same for second string, but over the results from the first grep.

  • The -Z argument to grep and the -0 argument 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.

share|improve this answer
    
Awesome thank you. Can you enlighten me as to what xargs is? –  Alex Ford Aug 4 at 17:26
2  
@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 without xargs, and you will see the problem (grep -l "first string" * | grep -l "second string") –  jim Aug 4 at 17:35
1  
@ntoskrnl - you will get a "(standard input)" message. A good explanation is this one, from Joseph R. –  jim Aug 4 at 20:01
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 Aug 4 at 20:04
1  
@Ajedi32 - you are correct - my bad. Edited answer :-) Thanks! –  jim Aug 4 at 20:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.