Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare first column of one file with the first column of second and print associated column of each if there was a match

I have two files, I need to compare their first columns and if the match is found, I'd like to output the corresponding values from both files.

Similar to this Q but I'd like to print columns from both files not one: How to compare multiple columns in two files and retrieve the corresponding value from another column if match found

File1.txt

adeqY   33.7
AIsLX   65.6
AmuBv   1589.0
aZMIx   84.4

File2.txt

AmuBv foo
iwwlp bar
adeqY hi
qUbJZ bye

Output

hi 33.7
foo 1589.0

I have the following awk command but I only managed to print the second column match from File2:

awk 'FNR==NR{a[$1]; next} ($1) in a {print $2 a[$2]}' File1.txt File2.txt

a[$2] doesn't want to print

Thanks in advance.

like image 262
eskp Avatar asked Sep 05 '25 02:09

eskp


1 Answers

Could you please try following.

awk 'FNR==NR{a[$1]=$2;next} ($1 in a){print $2,a[$1]}' Input_file1  Input_file2

Output will be as follows.

foo 1589.0
hi 33.7

Problem in your attempt: You was going good only thing in FNR==NR condition your a[$1] is NOT having any value it only created its index in array a so that is why it was not able to print anything when 2nd Input_file is being read.

like image 93
RavinderSingh13 Avatar answered Sep 06 '25 14:09

RavinderSingh13