Obtain patterns from a file, compare to a column of another file, print matching lines, using awk

awk, grep, sed, unix

Solution

The example you found is indeed very close to what you want, the only difference is that you don't want to match the whole line (`$0`).

Modify it to something like this:

awk 'NR==FNR { pats[$0]=1; next } { for(p in pats) if($2 ~ p) { print $0; break } }' patterns file

If you only need a fixed string match, use the `index()` function instead, i.e. replace `$2 ~ p` with `index($2, p)`.

You could also provide the column number as an argument to awk, e.g.:

awk -v col=$col 'NR==FNR { pats[$0]=1; next } { for(p in pats) if($col ~ p) { print $0; break } }' patterns file

Edit - whole field matching

You can accomplish this with the `==` operator:

awk -v col=$col 'NR==FNR { pats[$0]=1; next } { for(p in pats) if($col == p) { print $0; break } }' patterns file

Problem

I'd essentially like to combine the power of ``` grep -f ``` with ``` awk '{ if($2=="this is where I'd like to input a file of fixed string patterns") print $0}' ``` Which is to say, I'd like to search a specific column of a file (File 1) with an input file of patterns (File 2). If a match is found simply: ``` > outputfile.txt ``` From a previous post, this awk line is really close: ``` awk 'NR==FNR{a[$0]=1;next} {n=0;for(i in a){if($0~i){n=1}}} n' file1 file2 ``` Taken from Obtain patterns in one file from another using ack or awk or better way than grep? But it doesn't search a specific column of file 1. I'm open to other tools as well.

Original source

Related problems