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!
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 :
Please
Oops, I must've been sleeping when I wrote that!!!
Corrected and the required changes done in my earlier post.
Thanks a lot!
You've saved my lazy ass again
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