lolren
lolren

Reputation: 29

Calculate average in bash with more than 3 decimals

I am trying to calculate the average of some numbers in a file, in bash. I know awk does that perfectly with

awk '{s+=$1} END {print "Average: " s/NR}' file

but it's only giving me 3 decimals output. While that is enough in some cases, I need 7 decimals . How can I do that?

Upvotes: 1

Views: 170

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Following awk may help you on same.

awk '{sum+=$1} END{print sum/FNR}' OFMT="%0.9g"  Input_file

Upvotes: 0

Kusalananda
Kusalananda

Reputation: 15603

When printing the value, use printf with an appropriate format string:

awk '{ s += $1 } END { printf("%.7f\n", s/NR) }' file

Upvotes: 1

Related Questions