0
votes

I took reference from following link for comparing two files : Compare files with awk

awk 'NR==FNR{a[$1];next}$1 in a{print $2}' file1 file2

It prints 2nd column of file2, if 1st column of file2 found in file1.

But my requirement is little different. how to print 2nd column of file1 if 1st column of file2 found in associative array (built with 1st column of file1) ?

1

1 Answers

1
votes

With this:

awk 'NR==FNR{a[$1]=$2;next}$1 in a{print a[$1]}' file1 file2

With this way you assign a value to each array element of array a. For a line with fields foo bar, you actually create a[foo]=bar.
If you later give a command {print a[foo]} it will print bar (it's assigned value)

The previous {a[$1];next} creates an array with name a and index $1,but value is null; It is a stortcut of a[$1]="".

The whole thing works in awk, because awk has an easy way to look up indexes in an array using $1 in a{print something}. This is an awk if then shortcut. It is the same like {if ($1 in a) {print something}}. The great about this is that the part $1 in a refers to array a indexes and not array values.