How can I perform a second grep on the files returned from a previous grep?

5

3

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.

Chev

Posted 2014-08-04T16:57:11.237

Reputation: 343

Answers

9

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.

jimm-cl

Posted 2014-08-04T16:57:11.237

Reputation: 1 469

Awesome thank you. Can you enlighten me as to what xargs is? – Chev – 2014-08-04T17:26:46.207

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")

– jimm-cl – 2014-08-04T17:35:40.297

What is the problem with that command line? I don't have an OS X or Linux system at hand to test on. – ntoskrnl – 2014-08-04T19:51:36.823

1

@ntoskrnl - you will get a "(standard input)" message. A good explanation is this one, from Joseph R.

– jimm-cl – 2014-08-04T20:01:39.323

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 – 2014-08-04T20:04:47.767

1@Ajedi32 - you are correct - my bad. Edited answer :-) Thanks! – jimm-cl – 2014-08-04T20:11:56.767