Repeating awk command

Hi all,

I have an awk command that needs to be ran multiple times in a script on one file containing lots of fields of data.

The file look like this (the numbers are made up):

1234      2222     2223     2222
123        2223     3333    2323
3333      3321     3344    4444 

The file contains more fields than that but that's how it looks.

The command works out the average number from each field but to execute in the script could mean repeating it up to 72 times! (there could be up to 72 fields of data in the file).

The command

awk '{ s += $1 } END { print s/NR }' datafile > avefile

This works out to average of field 1 ($1) and puts it into avefile - I want to avoid having to do that for 72 lines in the script, obviously redirecting the subsequent output to the avefile. Is there any way of making the command run in the script with out the need of printing it some many times.

Thanks for any responses.

To run a piece of code multiple times, use a while or for loop, but you don't need to do that; it can all be done with a single awk script:

awk '{
for ( n = 1; n <= NF; ++n ) tot[n] += $n
if ( NF > max ) max = NF
}
END {
for ( n = 1; n <= max; ++n ) printf "Field %d: %d\n", n, tot[n] / NR 
}
' datafile > avfile

Thank for your response, much appreciated.

/nistleloy