Using AWK to Process Input from Multiple Files

awk

Solution

awk 'FNR==NR{a[$1]=$2 FS $3;next}

here we handle the 1st input (file2). say, FS is space, we build an array(`a`) up, index is column1, value is `column2 " " column3` the `FNR==NR and next` means, this part of codes work only for file2. you could man gawk check what are NR and FNR

{ print $0, a[$1]}' file2 file1

When `NR != FNR` it'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,

1st input has 5 lines
2nd input has 10 lines,

NR would be 1,2,3...15
FNR would be 1...5 then 1...10

you see the trick of `FNR==NR` check.

Problem

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.

Original source

Related problems