tags:

views:

4457

answers:

3

I want to pipe the output of grep as the search patter for another grep.

As an example:

grep <Search_term> <file1> | xargs grep <file2>

I want the output of the first grep as the search term for the second grep. The above command is treating the output of the first grep as the file name for the second grep. I tried using -e option for the second grep but it does not work either

+2  A: 

If using Bash then you can use backticks:

> grep -e "`grep ... ...`" files

the -e flag and the double quotes are there to ensure that any output from the initial grep that starts with a hyphen isn't then interpreted as an option to the second grep.

Note that the double quoting trick (which also ensures that the output from grep is treated as a single parameter) only works with Bash. It doesn't appear to work with (t)csh.

Note also that backticks are the standard way to get the output from one program into the parameter list of another. Not all programs have a convenient way to read parameters from stdin the way that (f)grep does.

Alnitak
this does not work, the output of the inner grep is a list of search terms and it is treating all but the first search term as file names
ok, changed now for compatibility with multiple search terms, so long as you're using bash.
Alnitak
this one works great , thanks
This one might have a problem if the first grep returns more than one result.
Paul Tomblin
+5  A: 

Try

grep ... | fgrep -f - file1 file2 ...
Paul Tomblin
what does this do?
Nathan Fellman
It uses the output of the first grep as the grep pattern for the second grep, as the question asked.
Paul Tomblin
@Nathan, it uses the output of the first grep as the input file of patterns for fgrep. "-f -" is the normal way of telling a unix program to use standard input as the input file if it normally takes an input file. Traditionally fgrep was the only grep that took a file as input, although it's possible that Gnu has modified the other greps.
Paul Tomblin
oh... I missed the standalone "`-`". Thanks!
Nathan Fellman
+4  A: 

You need to use xargs's -i switch:

grep ... | xargs -ifoo grep foo file_in_which_to_search

This takes the option after -i (foo in this case) and replaces every occurrence of it in the command with the output of the first grep.

This is the same as:

grep `grep ...` file_in_which_to_search
Nathan Fellman