pogibas
pogibas

Reputation: 28329

grep file content from piped content

My dummy file looks like this

cat dummy_file 
    Tom
    Jerry

My piped content looks like this

COMMAND | 
    Tom Cat
    Jerry Mouse
    Spike Dog

I want to grep only those piped lines that are in dummy_file.
I can do this by creating intermediate file.

COMMAND > intermediate_file  
grep -w -F -f dummy_file intermediate file 
    Tom Cat 
    Jerry Mouse

How can I achieve this without creating an intermediate file and just grep'ing piped content?
Tried this, but it doesn't work:

COMMAND | 
    xargs -I {} grep -w -F -f dummy_file -- NO RESULT

Or this:

COMMAND |  
    xargs -I {} grep {} -w -F -f dummy_file -- ALL LINES ARE PRINTED 

Upvotes: 3

Views: 154

Answers (2)

Idriss Neumann
Idriss Neumann

Reputation: 3838

You could use join command ;)

join --nonocheck-order -j1 <(COMMAND|sort) <(cat dummy_file|sort)|cut -d -f1 
# -j1 indicates the column to join in the two commands output
# it's equivalent to -11 -11 (first and second output)
# cut to print only the first column which is common to two orders 

See man join for more details.

Upvotes: 0

damienfrancois
damienfrancois

Reputation: 59090

grep accepts input from stdin. Just do

COMMAND | grep -w -F -f dummy_file 

Upvotes: 2

Related Questions