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.
Macos – How to perform a second grep on the files returned from a previous grep
bashgrepmacmacosterminal
Best Answer
First
grep
will return the files containingfirst string
.Second
grep
will do the same forsecond string
, but over the results from the firstgrep
.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.