I have a while loop which reads data from a file with city names:
city_name:
COIMBATORE
MADURAI
PONDICHERRY
SALEM
TRIPUR
TIRUCHI
TIRUNELVELI
TUTUCORIN
VELLORE
and using an awk
command within the while
loop and trying to read the variable defined in while loop body again in the awk
statement however, this is not working and giving me errors. I understand that the awk
requires the variables to be defined for its body separately to enable awk
to understand the variable usage and could read its value.
My while loop is like the following:
while read city
do
awk -F, '{
if ( $1 == "ACTIVE" ) &&
( $2 == "$city" )
print $1
}' siteDBName >> count
SUM=`awk '{ sum += $1 } END { print sum }' count`
done < city_name
where the siteDBName file contains the multiple columns with data like the following:
siteDBName:
ACTIVE,COIMBATORE,MGT500,1,5,7....
INACTIVE,MADURAI,GT500,5,6,7...
ACTIVE,SALEM,TR600,6,4,6...
ACTIVE,COIMBATORE,GT500,4,5,6...
..
..
Here, i tried using the awk -v c=$city
along with rest of the statements but this too gave me errors.
How can i use the variable used and initialized in the while loop inside the awk statement inside this while loop?
$city
, withawk -v c=$city
, you must use variablec
insideawk
instead. Your best choice should be passing through environment variablec=$city awk ...
then insideawk
, useENVIRON["c"]
awk -v c=$city
? as cuonglm states you must usec
inside awk to referer to the while loop's city. Have in mind thatc
inside awk must be referenced without the $ (it's not bash, it's awk) just c (for instance {print c})