12

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 1

14
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.

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.