Calculating average from files

I have some files with the following contents.I would like to calculate average of fifth column. How can I do this with awk?

file1

cat 95.9    152 78.0    17.9
rat 67.1    153 36.5    30.6
dog 81.4    154 68.1    13.3
dog 92.0    155 55.5    36.5
rat 73.8    156 23.9    49.9
file2

rat    79.0     157  64.3   14.7
fish   67.7     158  4.9    62.8
goat   90.2     159 80.7    9.5
dog    130.8    160 25.1    105.7

desired output

cat    17.9
rat    31.73
dog    51.83
fish   62.8
goat   9.5

I used the following code to calculate average. But the output is wrong.

awk '{a[$1]+=$5}END {for (i in a) {print i,a;Total+=a}; print "average - ", Total/NR}' *
rat 95.2
goat 9.5
fish 62.8
cat 17.9
dog 155.5
average -  37.8778
1 Like

Hello avina,

Welcome to forums, a special thanks to you for using code tags for commands/codes/Inputs you had used in your post. Could you please try following and let me know if this helps you.

awk 'FNR==NR{A[$1]+=$5;B[$1]++;next} {A[$1]+=$5;B[$1]++} END{for(i in A){print i OFS A/B}}' File1 File2

Output will be as follows.

cat 17.9
dog 51.8333
rat 31.7333
fish 62.8
goat 9.5

Thanks,
R. Singh

1 Like

Hi Singh,

Thank you very much for your help.

awk 'BEGIN{
FS="[ ]+"
}
{
arr[$1]+=$5
brr[$1]+=1
}
END{
	for(i in arr){
		avg=arr/brr
		print i,avg
	}
}' a b

Saying "the output is wrong" doesn't help us much. What, in the output you are getting, is wrong? With your sample input, what output are you trying to get? The output you said you want does not show the sum of values for each animal nor the average value for each animal (except for animals that only appear in one of your input files). Are you trying to prints animal sums in the output, or animal averages?

What values are you trying to average in your final line of output? Are you trying to calculate the average of all of the input values (which seems to be what your code is doing)? Are you trying to calculate the average of the averages for each animal? Are you trying to calculate the average of the sums for each animal?