EGOPOLY

Topics include: programming, Apple, Unix, gadgets, large-scale web sites and other nerdy stuff.

How to average a series of numbers in a shell script

2007-07-06 15:16:56

Often I have a bunch of numbers (like transfer sizes from an httpd log file) and I want to get the average in a shell script, without pasting into an excel sheet.

Here's one way to do it. In this example, I want to calculate the average size of a cgi output. In my apache log format, column 7 is the transferred size in bytes.

grep 'GET /someurl.cgi' accesslog | cut -f7 | awk '{total += $1;count += 1;printf"avg = %d\n", total/count}' | tail -1