Read a file and pipe to grep

2

1

Wondering if anyone can help me, I'm very rusty with bash and seem to hit a bit of an impasse.

I'm storing a list of strings in a file and would like to read the file and pipe each line returned to grep which in turn searches a directory for files containing the string.

Initial attempt:

cat filename | grep -lr *

However this is not returning any output.

Can anyone give me some directions on the best approach?

user675366

Posted 2011-05-26T13:08:07.417

Reputation: 21

Answers

3

Avoid that useless use of cat. You can of course solve this with xargs and the like. But that's over-complex compared to a simple while loop.

while read i 
do
    grep -r -- "$i" directory/
done < filename

JdeBP

Posted 2011-05-26T13:08:07.417

Reputation: 23 855

1Are you sure about that peth? Pretty sure it finishes after the last line of filename. – Pricey – 2011-06-02T09:21:07.417

Ah apologies, never saw the sneaky edit. Never used the pipe up there before either.. – Pricey – 2011-06-02T13:01:39.020

2

I would try this.

cat filename | while read line ; do grep -lr "$line" * ; done

You could also pipe it to "sort -u" so you don't get duplicate.

chuck

Posted 2011-05-26T13:08:07.417

Reputation: 504