Problem using shell variable in awk if condition

Hi friends,

     I'm having a bit of a problem using shell variable in an awk if statement.

Please note that i'm using -v option as listed in many forums but I still don't get it working. Here's my code. Kindly help as I've gone crazy trying to work this out :wall:

#!/bin/bash -xv

fnStats()
{
modes=("${!1}")
services=("${!2}")
dates=("${!3}")
prices=("${!4}")
for (( i = 0 ; i < ${#dates[@]} ; i++ )) do
echo "${dates[$i]}" > /home/sm_stats.txt
for (( j = 0 ; j < ${#services[@]} ; j++ )) do
for (( k = 0 ; k < ${#modes[@]} ; k++ )) do
for (( l = 0 ; l < ${#prices[@]} ; l++ )) do
a=$(grep "CHG=1,${prices[$l]}" TLOG_BILLING_REALTIME_${dates[$i]}* | awk -v s="${services[$j]}" -v m="${modes[$k]}" 'BEGIN {FS = "|"} {if($8=="A" && $7==s && $11==m) print $4}' | wc -l)
echo -n "$a," >> /home/sm_stats.txt
#echo "${dates[$i]} ${services[$j]} ${modes[$k]} ${prices[$l]} $a"
#echo "TLOG_BILLING_REALTIME_${dates[$i]}*"
done
done
done
done
}

cd /SUBMGR/Tomcat/logs/TLOG/BILLING_REALTIME

modes=(OBD VP WEB SMS PRESSSTAR)
services=(RBT_ACT_DEFAULT RBT_ACT_COPY RBT_ACT_GIFT)
prices=(5.0 2.5 1.0)
dates=(20120529)

fnStats modes[@] services[@] dates[@] prices[@]

In the code, i'm trying to get values from different loops and substituting it in the awk part of the code.

Infact, i turned on the debug option of bash and could see the below output when it was executing that particular line of code.

grep "CHG=1,${prices[$l]}" TLOG_BILLING_REALTIME_${dates[$i]}* |  awk -v s="${services[$j]}" -v m="${modes[$k]}" 'BEGIN {FS = "|"}  {if($8=="A" && $7==s && $11==m) print $4}' | wc -l
++ awk -v s=RBT_ACT_GIFT -v m=PRESSSTAR 'BEGIN {FS = "|"} {if($8=="A" && $7==s && $11==m) print $4}'
++ wc -l
++ grep CHG=1,1.0 TLOG_BILLING_REALTIME_20120529_000000..log

As you see above, it substitutes the corresponding loop variable value in the first part of the statement, but doesn't do so in the "if" condition!

I am suspecting the single quote before 'BEGIN' which i think needs to be escaped. But i've tried that only to get a syntax error :frowning:

s and m are not supposed to be substituted by bash. What happens within awk can not be made visible by the shell debug options.

Thanks for helping Scrutinizer.

In that case, can you please let me know what else could be the problem since i'm not getting the desired output?

I don't know, could you post an input sample and a corresponding (desired) output sample and what you are trying to achieve?

Never mind friend. Thanks a lot for your time.

I figured out that the pipe '|' was causing the problem. So, i redirected the output of grep to a file and used that file as an input to awk.

It seems to be working now.

Having said that, still trying to figure out why pipe "|" is not working.

Cheers :slight_smile: