How to take average of each line

I have data like this. I would like to take averages like the output:

1. 800
2. 900 
3. 1000
4. 1100
5. 1200

This command does not work as I expected. It shows 0 for all. Could anyone help me to correct it?

cat tcat test.txt | awk '{ sum=0; for (counter = 1; counter >= 5; counter++) sum+=$2; print sum/counter}'

Expected output

1  800 # 800/1
2  850 #(800+900)/2
3  900 #(800+900+1000)/3
4  950 #(800+900+1000+1100)/4
5 1000 #(800+900+1000+1100+1200)/5

>Solution :

With your shown samples please try following.

awk '{print $1,($2+sum)/FNR;sum+=$2}' Input_file

OR in case your first field’s DOTs you want to remove like your shown samples then try following a little tweak in above code:

awk '{sub(/\.$/,"",$1);print $1,($2+sum)/FNR;sum+=$2}' Input_file

OR if your shown examples 1.(first fields) and so on is just for reference then use $0 as follows:

awk '{print ($0+sum)/FNR;sum+=$0}' Input_file

Explanation: Simple explanation would be, using print function of awk in which printing $1(first field) along with value(sum of 2nd field with sum and divide this with $2), then keep on add the 2nd field value into sum variable(as per requirement).

Leave a Reply