tim
tim

Reputation: 467

Taking result of a grep search and using it to search another file. linux bash script

I am trying to search the file dep/playlist for 'ohn'. Then, I would like to take this result and apply it to a new grep command that searches the file employee list end then echoes the results on screen. The code below isn't behaving as expected.

grep ohn dep/playlist > search
grep $(cat search) employeelist > newlist
cat newlist

Thanks,

Tim

Upvotes: 0

Views: 52

Answers (2)

millinon
millinon

Reputation: 1576

xargs:

grep ohn dep/playlist | xargs -I name grep name employeelist

This searches dep/playlist for 'ohn', and then upon finding a result, that result is then used in grep X employeelist, where X is the result from the first grep.

Upvotes: 0

devnull
devnull

Reputation: 123708

You need to tell grep to obtain the patterns from a file, use the -f option:

   -f FILE, --file=FILE
          Obtain  patterns  from  FILE,  one  per  line.   The  empty file
          contains zero patterns, and therefore matches nothing.   (-f  is
          specified by POSIX.)

So the command would look like:

grep -f search employeelist > newlist

Using process substitution you could obviate the need of a temporary file. So the two grep commands could be written into one as:

grep -f <(grep ohn dep/playlist) employeelist > newlist

Upvotes: 4

Related Questions