user11805177
user11805177

Reputation:

How to calculate average per row (awk command)

I have a file with 269 countries. 10 columns each country. I need to create a script that will average calculation of Japan from the 5-10 column and save the average in a new file like : Japan,JPN,Forest area (% of land area)= "(The average number)".

My file is. Csv I don't need all the country average. I just want to calculate average of Japan.

Jordan,JOR,Forest area (% of land area),AG.LND.FRST.ZS,1.0982203199,1.0982203199,1.0982203199,1.0982203199,1.0982203199,1.0982203199,,
Japan,JPN,Forest area (% of land area),AG.LND.FRST.ZS,68.4844328624,68.4791046618,68.4737766074,68.4693877551,68.4649989028,68.4606100505,,
Kazakhstan,KAZ,Forest area (% of land area),AG.LND.FRST.ZS,1.2256917435,1.2256917435,1.2256917435,1.2256917435,1.2256917435,1.2256917435,,

Upvotes: 0

Views: 495

Answers (1)

Frank-Rene Schäfer
Frank-Rene Schäfer

Reputation: 3342

Solution:

awk -v country=Japan 'BEGIN{FS=","}{ if( $1==country ) { n=0; for(i=5;i<NF;++i) { if( $i ) { ++n; sum += $i; } } print country ": " sum/n; }}' infile.txt

Variable country can be set at wish. The fields from 6 to end are summed up and divided by the number of entries to get the avarage.

Upvotes: 1

Related Questions