Awk compare 2 files, print match together with non match lines filled with 0

awkjoin;text processing

I have two files.

I want to match the 1st column of first file to 1st column of second file. If there is a match I'd like to print the 2st column of second file, if not 0.

I have tried awk
(awk 'FNR==NR{a[$1]=$0;next} {print a[$1]}' 2.txt 1.txt) but it is not working.

F1.txt

A
B
C
D
E
F
G
H
I
J

F2.txt

A  0.5
E   1
H   0.5
J    1

Desired_output

A    0.5
B    0
C    0
D    0
E    1
F    0
G    0
H    0.5
I    0
J   1

Best Answer

Assuming your input files are tab-delimited:

$ join -a 1 -e 0 -t $'\t' -o 1.1,2.2 F1.txt F2.txt 
A   0.5
B   0
C   0
D   0
E   1
F   0
G   0
H   0.5
I   0
J   1

join the two files, ensure all lines in the 1st file are present (-a), if any fields are null then use the value "0" (-e), take the first field from the first file and the 2nd field from the 2nd file (-o), and use tab as the delimiter (-t)

If you want awk, I'd write (note the order of the file arguments)

awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$1]=$2; next} {print $1, (v[$1] ? v[$1] : 0)}' F2.txt F1.txt
Related Question