Number of elements, average value, min & max from a list of numbers using awk

Hi all,

I have a list of numbers. I need an awk command to find out the numbers of elements (number of numbers, sort to speak), the average value the min and max value. Reading the list only once, with awk.

Any ideas?

Thanks!

Since you haven't provided any samples, I'll just throw in a solution with assumptions:

awk '{total+=$1;c++}
$1<=min{min=$1}
$1>=max{max=$1}
END{
OFMT="%.6f"
print "Total numbers   : " c
print "Smallest number : " min
print "Largest number  : " max
print "Average         : " total/NR}' file

Thank you. It only lacks 2 things :

  • I guess there's a missing "}" in your statement, I've added at the end of the command, it works.
  • I also need the number of numbers (number of elements in the list), not the "total". The total I know it is necessary for the average value, but I don't needed it printed, I need the number of elements in the list instead.

Please :smiley:

Oops, I must've been sleeping when I wrote that!!!
Corrected and the required changes done in my earlier post.

1 Like

Thanks a lot!
You've saved my lazy ass again :stuck_out_tongue:

May I propose a few enhancements/corrections to elixir_sinari's post:
a) c will be identical to NR even if empty lines are encountered, so it can be replaced by NR and left out OR we need to check for empty lines, e.g. NF>0 .
b) min and max will be empty and either of them will stay empty as long as 0 is not traversed. They should be initialized.
c) min and/or max will be distorted by empty lines, so a check for that will be mandatory.
Pls try:

awk 'NR==1  {min=max=$1}
     NF > 0 {total+=$1; c++;
             if ($1<min) {min=$1}
             if ($1>max) {max=$1}
            }
     END {OFMT="%.6f"
          print "Total numbers   : " c
          print "Smallest number : " min
          print "Largest number  : " max
          print "Average         : " total/c}
    ' file
1 Like