1834458 Members
3090 Online
110067 Solutions
New Discussion

ave and max

 
SOLVED
Go to solution
Lexxx
Advisor

ave and max

Hi Guys,
I have a file which contains numbers (some of them decimals). For each file has different word count (wc -l). I computed for each the average and maximum value. I did use for loops like for i in `cat file`
do
x = `expr $x + i | bc -l`
done
x is at initial zero then I use it as well by checking max by "if" logic.
But it requires time so I may ask if you have any idea how can I use awk in it for the average and maximum values in that file.
Will appreciate your help. Regards....

4 REPLIES 4
Dennis Handly
Acclaimed Contributor
Solution

Re: ave and max

Assuming one per line:
awk '
BEGIN { max=-2000000000; sum=0; count=0 }
{
count++
sum+=$1
if ($1 > max)
max = $1
}
END {
print "average:", sum/count
print "max:", max
} ' file

I suppose NR could be used instead of count.
Arturo Galbiati
Esteemed Contributor

Re: ave and max

Hi,
assuming one value per line:
(/> is my prompt)

/> cat f1
1.5
2
4
0.5
0

To get what you need:
/> sort -nk1 f1|awk '{t+=$1};END {print "Total=" t " Lines=" NR " AVG=" t/NR " MAX=" $1}';
Total=8 Lines=5 AVG=1.6 MAX=4

I print Total and Lines for debug, but you can avoid this.

HTH,
Art
Peter Nikitka
Honored Contributor

Re: ave and max

Hi,

I don't understand what you mean by
>>
For each file has different word count (wc -l)
<<

Do you have to parse several files, all containing numbers you want to do calculation with? You can use the awk internal variables 'FILENAME' and 'FNR' for this.
Next: is there only one number per line or do you have multiple entries per line? You would have to
- loop over all (valid?) fields of line in that case (e.g. for(i=1;i<=NF;i++) ...).
- add the number of fields instead of using FNR (e.g. num+=NF)
in that case.

awk 'BEGIN {max="undef"}
FILENAME && FILENAME != lastf {printf("max=%s avg=%s\n", max,sum/FNR); max="undef"; sum=0 }
{lastf=FILENAME; sum+=$1; if(max=="undef") max=$1; else if($1>max) max=$1 }
END {printf("max=%s avg=%s\n", max,sum/FNR)}' file1 file2 ...

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Dennis Handly
Acclaimed Contributor

Re: ave and max

>Peter: I don't understand what you mean by

I assumed that the script would have to calculate the number of records and couldn't be a constant.