Tuesday, March 24, 2009

AWK Can Do Lookup, with ease

Some time ago, I blogged about AWK can do lookup. In fact, you can handle that with ease if your AWK supports FNR. FNR is the input record number in the current input file. If the first filename to AWK contains the lookup mapping, you can get AWK to store the lookup if FNR==NR. FNR==NR is always true for the first file processed by AWK. For subsequent files, FNR will be reset to 1 and therefore FNR==NR condition will no longer be true.

Below simple example demonstrates the power of FNR

file1.txt contains the lookup mapping and lookup will be applied to file2.txt and file3.txt

$ cat file1.txt
1 First
2 Second
3 Third
4 Fourth
5 Fifth

$ cat file2.txt
swimming 1
table-tennis 3
cycling 2
running 1
tennis 3

$ cat file3.txt
perl 4
python 3
tcl 2
shell-script 2

$ awk 'FNR==NR{map[$1]=$2;next}{print $1,map[$2]}' file1.txt file2.txt file3.txt
swimming First
table-tennis Third
cycling Second
running First
tennis Third
perl Fourth
python Third
tcl Second
shell-script Second

FYI, Solaris /usr/bin/awk does not support FNR and you have to use nawk



Post a Comment

<< Home