Many people have been very helpful by posting the following solution for AWK’ing multiple input files at once:
$ awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' file2 file1
This works well, but I was wondering if I someone could explain to me why? I find the AWK syntax a little bit tough to get the hang of and was hoping someone wouldn’t mind breaking the code snippet down for me.
here we handle the 1st input (file2). say, FS is space, we build an array(
a) up, index is column1, value iscolumn2 " " column3theFNR==NR and nextmeans, this part of codes work only for file2. you could man gawk check what are NR and FNRWhen
NR != FNRit’s time to process 2nd input, file1. here we print the line of file1, and take column1 as index, find out the value in array(a) print. in another word, file1 and file2 are joined by column1 in both files.for NR and FNR, shortly,
you see the trick of
FNR==NRcheck.