shell script - unexpected result

I hv a file --am executing a script which is giving me unexpected results

COntents of file:

f1

CMT_AP1_CONT:/opt/sybase/syboc125:150:ASE12_5::Y:UX:
CMT_AP1:/opt/sybase/syboc125:150:ASE12_5::Y:UX

f1.tmp

CMT_AP1_CONT:/opt/sybase/syboc125:150:ASE12_5::Y:UX:
CAT_AP1:/opt/sybase/syboc125:150:ASE12_5::Y:UX

Difference is at 2nd line "CMT" and "CAT"

Script#1

for i in `grep AP1 f1 |awk -F: '{print $1}'`
do
  DSQUERY=$i
  A15F=`grep AP1  f1| grep ${DSQUERY} | awk -F: '{print $3}'`
  echo "$A15F ----- $i"
  if [ "$A15F" = "150" ]; then
    echo $i
  else
   echo "Version 12.5",$i
  fi
done

ouput:

150 ----- CMT_AP1_CONT
CMT_AP1_CONT
150
150 ----- CMT_AP1
Version 12.5,CMT_AP1

Script#2:

for i in `grep AP1 f1 |awk -F: '{print $1}'`
do
  DSQUERY=$i
  A15F=`grep AP1  f1| grep ${DSQUERY} | awk -F: '{print $3}'`
  echo "$A15F ----- $i"
  if [ "$A15F" = "150" ]; then
    echo $i
  else
    echo "Version 12.5",$i
  fi
done

Output 2:

150 ----- CMT_AP1_CONT
CMT_AP1_CONT
150 ----- CAT_AP1
CAT_AP1

++++++expected behaviour is 2 why script #1 is not working in a desired way..Pls hlelp me..Thanks

This should work

for i  in  `grep AP1 f1 |awk -F: '{print $1}'`
do
DSQUERY=$i
export A15F
A15F=`grep AP1 f1| grep -w ${DSQUERY} | awk -F: '{print $3}'`
echo "$A15F ----- $i"
if [ "150" = "$A15F" ]; then
echo $i
else
echo "Version 12.5",$i
fi
done

This is because the second time the for loop runs it select both the lines "CMT_AP1" matches both line as a result A15F is 150 new line 150 which doesnt match 150

useless use of grep | awk -- awk can handle searching for DSQUERY itself. Also useless use of backticks, the latter of which can actually be dangerous -- that splits on whitespace, not just lines, for one thing. It may truncate a list that ends up too long for a shell variable to hold too.

awk -F: '/'${DSQUERY}'/ { print $3 }' | while read LINE
do
...
done

Side-effect of the pipe means variables set inside the while loop may not be visible outside it. To avoid this you can send the output into a temp file, then read the temp file like done < /path/to/file