USSR|8650|262|Asia
Canada|3852|24|North America
China|3692|866|Asia
USA|3615|219|North America
Brazil|3286|116|South America
India|1269|637|Asia
Argentina|1072|26|South America
Sudan|968|19|Africa
Algeria|920|18|Africa
I have written a shell program which is not working. Pl help me where i am going wrong
FILE=/path/a.sh
area=0
total=0
for area in `grep a.sh | awk -F'|' '{print $2}'`
do
total=$(($total+$area))
done
echo $total
I tried with matrixmadhan and aigles, But it is not working.
USSR|8650|262|Asia
Canada|3852|24|North America
China|3692|866|Asia
USA|3615|219|North America
Brazil|3286|116|South America
India|1269|637|Asia
Argentina|1072|26|South America
Sudan|968|19|Africa
Algeria|920|18|Africa
***************
FILE=/path/a.sh
area=0
total=0
for area in `awk -F'|' '{print $2}' $FILE`
do
total=$(($total+$area))
done
echo $total
to my above shell scripts is working fine for one sum(column). How to use more than one col for sum ie $2 and $3 i want the sum
USSR|10|20|Asia
Canada|20|30|North America
China|30|40|Asia
I tried with era code, but is is giving wrong output
`awk -F '|' '{ area+=$2; total+=$3; }
END { print "area: " area; print "total: " total }'` /path/a.sh
awk: syntax error near line 1
awk: bailing out near line 1
/path/a.sh: USSR: not found
/path/a.sh: 10: not found
/path/a.sh: 20: not found
/path/a.sh: Asia: not found
/path/a.sh[2]: Canada: not found
/path/a.sh[2]: 30: not found
/path/a.sh[2]: 20: not found
/path/a.sh[2]: North: not found
/path/a.sh[3]: China: not found
/path/a.sh[3]: 40: not found
/path/a.sh[3]: 30: not found
/path/a.sh[3]: Asia: not found
echo $area
40
echo $total
150
It gave the following output. It is supposed to give the output as 60 and 90It has some error also. Pl help me
You forgot the "set --" which needs to go before the backticks. It causes the positional parameters to be filled with the output from the command in the backticks. (So $1 is whatever awk echos in the first field, and $2 is the second field in the output, etc.)
vnix$ awk -F '|' '{ area += $2; population += $3; }
> END { print "area: " area; print "population: " population }' <<HERE
> USSR|10|20|Asia
> Canada|20|30|North America
> China|30|40|Asia
> HERE
area: 60
population: 90
vnix$
vnix$
vnix$ set -- `awk -F '|' '{ area+=$2; total+=$3; }
END { print "area: " area; print "total: " total }' <<HERE
> USSR|10|20|Asia
> Canada|20|30|North America
> China|30|40|Asia
> HERE
> ` # <- note closing backtick here
vnix$ echo $1
area:
vnix$ echo $2
60
vnix$ echo $4
90
You need to use either one or the other, not mix the two variants I posted.