How to pass variables to awk command with conditions?
You have two basic choices: i) use -v
to pass the variable to awk
or ii) close the '
around the awk
script, use the shell variable and continue the '
again.
Use
-v
while read city do awk -v city="$city" -F, '{ if ( $1 == "ACTIVE" && $2 == city ){print $1} }' siteDBName >> count done < city_name
Close the quote
while read city do awk -F, '{ if ( $1 == "ACTIVE" && $2 == "'$city'" ){print $1} }' siteDBName >> count done < city_name
I removed the SUM=
line since it wasn't doing anything useful given that $1
is ACTIVE
so adding it makes no sense. See my alternate approach below for a way to do this correctly.
Also, note that with this approach, you need to read the siteDBName
file multiple times. A more efficient version would be:
$ awk -F, '{
if(NR==FNR){cities[$1]++;}
else if($1=="ACTIVE" && $2 in cities ){sum++}
} END{print sum,"active cities"}' city_name siteDBName
3 active cities
Just as @cuonglm and @YoMismo stated, you are using the wrong variable and the wrong way to reference it. It should be something like:
while read city
do
awk -v c="$city" -F, '{
if ( $1 == "ACTIVE" && $2 == c )
print $1
}' siteDBName >> count
SUM=`awk '{ sum += $1 } END { print sum }' count`
done < city_name