I have file1 as follows:
2010,92614,0,1
2010,92614,4,1
and file2 as follows:
2010,0,907894
2010,1,17788
2010,2,2827
2010,3,1212
2010,4,669914
I would like to join the two files on fields 1 and 3 of file1 and fields 1 and 2 of file2 (e.g. 2010 and 0 for the first record in both files) and the output needs to look like this:
2010,92614,0,1,907894
2010,92614,4,1,669914
In other words, I need to append field 3 of file2 to file1 for matching rows. When I try the following code, it gives me the data from file1 but not field 3 of file2:
awk -F, 'NR==FNR {a[$1,$2]=$3; next} {print $0,a[$1,$2]}' OFS=, file2 file1
I get, incorrectly:
2010,92614,0,1,
2010,92614,4,1,
Notice the commas at the end but no data. I figured that it is probably because the matching fields are not adjacent to each other in file1. If I reorder the fields in file1 as follows,
awk -F, '{print $1,$3,$2,$4}' OFS=, file1 > file1_mod
then the join code works. My question is: How do I join without reordering the fields?
Please note that the native Bash 'join' command may be used with some tricks to enable it to join on more than one field, but I am not interested in that solution. I want to use awk.
print $0,a[$1,$3]
notprint $0,a[$1,$2]
print $0,a[$1,$2]
is a typo of the correctprint $0,a[$1,$3]
. I believe that the question could be closed.