3

I have two txt files with different lengths.

File 1:
Albania 20200305    0
Albania 20200306    0
Albania 20200307    0
Albania 20200308    0
Albania 20200309    3
Albania 20200310    7
Albania 20200311    4
Albania 20200312    2
File 2: 
Europe  Albania 20200309    2
Europe  Albania 20200310    6
Europe  Albania 20200311    10
Europe  Albania 20200312    11
Europe  Albania 20200313    23
Europe  Albania 20200314    33

I would like to create a File3 which will add the 3. column of the File1 at the end of File2 if 1st and 2nd column of File1 is same with 2nd and 3rd column of File2. It should look like this:

File3:
Europe  Albania 20200309    2   3
Europe  Albania 20200310    6   7
Europe  Albania 20200311    10  4
Europe  Albania 20200312    11  2

I have tried

awk 'NR==FNR{A[$1,$2]=$3;next} (($2,$3) in A) {print $0, A[$1,$2]}' file1.txt file2.txt > file3.txt

but it is just printing File 2, it does not add the third column of File1.

Can you please help me with the problem.

Thanks in advance!

ezgi koker
  • 93
  • 4

1 Answers1

4

Your approach is correct but while printing you need to use like A[$2,$3], you are using A[$1,$2] which is NOT existing(Because 1st, 2nd columns of file1 should be compared to 2nd and 3rd columns of file2) in array A hence its printing only current line values of file2 in your file3.

awk 'NR==FNR{a[$1,$2]=$3;next} (($2,$3) in a) {print $0, a[$2,$3]}' file1 file2

Also see link(Thanks to James for providing nice link here) Why we shouldn't use variables in capital letters

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93