abh
abh

Reputation: 101

compare columns

I have two files:

file1

1 
2 
3
4
5

file2

a     0     1    h    f  
b     0     3    h    f
c     0     8    h    f
d     0     5    h    f

I want to compare file1 to column3 of file2 and print the whole row of file2 like this

a     0     1     h    f
b     0     3     h    f 
d     0     5     h    f

I tried using awk but I am printing the column3:

awk 'NR == FNR {f2[$3]=$1; next} $1 in f2{print f2[$1],$1}' file2 file1

How can I print the whole rows from file2?

Upvotes: 2

Views: 177

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85785

Much easier if you give file1 first:

$ awk 'NR==FNR{a[$1];next}$3 in a' file1 file2
a     0     1    h    f
b     0     3    h    f
d     0     5    h    f

This way you can easily print the whole line in file2 if the value in field three is in file1. The default block is in awk is {print $0} so it can be omitted from $3 in a{print $0}.

Upvotes: 3

Related Questions