awk - Vlook up functionality

i am searching how to implement vlookup functionality in AWK

i have file1 as

100,A
200,B
300,C
600,B
400,C

and file2 as

A,1
B,2
C,3

and the output should be

100,A,1
200,B,2
300,C,3
600,B,2
400,C,3

can any help me in this :slight_smile:

Is this a homework assignment?

no this is not an assignment
i was trying to implement vlookup functionality and i was not getting

Try something like:

awk '
BEGIN { FS = OFS = "," }
FNR == NR { x[$1] = $2; next }
        { print $0, x[$2] }' file2 file1

If you are using a Solaris/SunOS system, change awk in the script above to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

Thank you very much Don this has worked out

gawk 'BEGIN{FS=OFS=","}NR==FNR{a[$1]=$2}NR>FNR{print $0,a[$2]}' file2 file1
100,A,1
200,B,2
300,C,3
600,B,2
400,C,3

---------- Post updated at 11:45 AM ---------- Previous update was at 11:42 AM ----------

My code does work too:

gawk 'BEGIN{FS=OFS=","}NR==FNR{a[$1]=$2}NR>FNR{print $0,a[$2]}' file2 file1

And what does "next" mean in your code? I'm a little confused.

The standards describe the meaning of the "next" statement as:

So, the "next" in my suggested code:

awk '
BEGIN { FS = OFS = "," }
FNR == NR { x[$1] = $2; next }
        { print $0, x[$2] }' file2 file1

skips to the next input record without evaluating the the last statement in my script. The condition NR>FNR before the last action in your suggested code makes your script produce the same output as my suggested code. My script doesn't look at the last statement when the condition FNR==NR is true; your code always evaluates NR>FNR even when it has already determined that FNR==NR .

Thanks, I got it. Your code is more efficient.