awk Match and Print

I have the following script in place that will print the values of FileB when the first column matches File A's first column.

awk 'NR == FNR {A[$1]=$2;next};$1 in A {print $1,$NF,$2,$3,A[$NF]}' FileA FileB

Input

FileA

3013   4

FileB

3013 2009 03 JUNK  43

Output

3013 43 2009 03

However, I need values from both files to be printed. Any suggestions?

Expected Output

3013 4  43  2009 03

Since you're matching on the 1st column in both files, you need A[$1] instead of A[$NF] . It looks like you want something more like:

awk 'NR == FNR {A[$1]=$2;next};$1 in A {print $1,A[$1],$2,$3,$NF}' FileA FileB

From your sample input it isn't clear why you're using $NF to print the last field instead of just printing $4 ; but with your sample input, it shouldn't matter.

If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .

1 Like

The $NF was left over from a previous task.

Thanks for the prompt response!