Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using each line of awk output as grep pattern

Tags:

grep

awk

I want to find every line of a file that contains any of the strings held in a column of a different file.

I have tried
grep "$(awk '{ print $1 }' file1.txt)" file2.txt
but that just outputs file2.txt in its entirety.

I know I've done this before with a pattern I found on this site, but I can't find that question anymore.

like image 549
sans Avatar asked Apr 27 '11 19:04

sans


2 Answers

I see in the OP's comment that maybe the question is no longer a question. However, the following slight modification will handle the blank line situation. Just add a check to make sure the line has at least one field:

grep "$(awk '{if (NF > 0) print $1}' file1)" file2

And if the file with the patterns is simply a set of patterns per line, then a much simpler version of it is:

grep -f file1 file2

That causes grep to use the lines in file1 as the patterns.

like image 121
Mark Wilkins Avatar answered Oct 10 '22 03:10

Mark Wilkins


THere is no need to use grep when you have awk

awk 'FNR==NR&&NF{a[$0];next}($1 in a)' file2 file1
like image 39
ghostdog74 Avatar answered Oct 10 '22 02:10

ghostdog74