compare two files using awk

Hi,

I want to compare two files using awk and write an output based on if the records matched.

Both the files are space delimitted.

File A:

8351 00000000000636 2009044 -00001.000
8351 00000000000637 2009044 -00002.000
8351 00000000000638 2009044 -00001.000
8351 00000000000640 2009044 -00003.000
8351 00000000000642 2009044 -00001.000
8351 00000000000650 2009044 -00001.000

File B:

8351 00000000000636 006
8351 00000000000637 002
8351 00000000000642 001
 

Output:

006 8351 00000000000636 2009044 -00001.000
002 8351 00000000000637 2009044 -00002.000
000 8351 00000000000638 2009044 -00001.000
000 8351 00000000000640 2009044 -00003.000
001 8351 00000000000642 2009044 -00001.000
000 8351 00000000000650 2009044 -00001.000

Basically, if the second column of File A matches with the second column of File B. I need to write the third column of file B and the complete line from File A.

If not matched I need to write 000 and then the complete line in File A.

I tried some awk commands.. but didnt work. This below code i wrote to get the matched record and write the third column and the file A. But the third column is not getting written.

Any help will be much appreciated.

awk '
NR==FNR{a[$2]=$2;next}
a[$2]{print a[$3] $0}' $ZEROSTOCK $INFILE > $INTEMP
 
awk '
  FNR==NR { fb[$2]=$3; next}
  { print (($2 in fb)? fb[$2] : "000"), $0 }
' fileB fileA
awk 'NR==FNR{a[$2]=$3;next}{if (a[$2]) printf a[$2]" "; else printf "000 "}1' zerostock infile
006 8351 00000000000636 2009044 -00001.000
002 8351 00000000000637 2009044 -00002.000
000 8351 00000000000638 2009044 -00001.000
000 8351 00000000000640 2009044 -00003.000
001 8351 00000000000642 2009044 -00001.000
000 8351 00000000000650 2009044 -00001.000

Would you mind explaining the script? why fb[$2]=$3 instead of $2?? I didnt actually get that part.

The key that needs to be stored is $2 and the value is $3 of the zerostock input file.

This worked. Thanks a lot.

I realize you asked about awk, but Unix "join" is also a good way to sart something like this.

For this case,

 join -1 1 a b

gives output like

nawk 'NR==FNR {
_[$2]=$3
}
NR!=FNR{
  if(_[$2]!="")
   print _[$2]" "$0
  else
   print "000 "$0
}' b a