Fetch lines from a file matching column2 of another file

Hi guys,
Please help me out in this problem. I have two files

FILE1
abc-23 : 4529675
cde-42 : 9824532
dge-91 : 1245367
gre-45 : 9824532
fgr-76 : 4529675

FILE2
4529675 : Gal Glu house-2-be
9824532 : cat mouse
1245367 : sirf surf-2-beta

where FILE2 is a static file with fixed contents.

I need an output file like this-

FILE3
abc-23 Gal Glu house-2-be
cde-42 cat mouse
dge-91 sirf surf-2-beta
gre-45 cat mouse
fgr-76 Gal Glu house-2-be

It should contain column 1 of FILE1 and column 2 of FILE2 where it matches column 2 of FILE1 with column 1 of FILE2.

Thanks.

one way to do it:

while read line
do
    str=`echo $line | cut -d' ' -f3`  &&  echo -n `echo $line | cut -d' ' -f1`  &&  grep $str file2 | cut -d' ' -f3-
done < file1

There is no space between column1 and 2 of the output

abc-23Gal Glu house-2-be
cde-42cat mouse
dge-91sirf surf-2-beta
gre-45cat mouse
fgr-76Gal Glu house-2-be

I need a tab between column1 and 2

this is a problem about mapping from two files which had been answered many times.

So, show us what have you tried before ? :slight_smile:

nawk 'BEGIN{FS=":"}
 {
 if(NR==FNR)
 {
	gsub(/ /,"",$1)
	t[$1]=$2
 }
 else
 {
	gsub(/ /,"",$2)
 	print $1"  "t[$2]
 }
 }' file2 file1

The code is working fine but If you could explain what's happening in the code I can understand it better.

Thanks,
smriti