Operating System - HP-UX
1752577 Members
4818 Online
108788 Solutions
New Discussion юеВ

Need to learn how to calculate averages for scripting

 
SOLVED
Go to solution
Wilson David
New Member

Need to learn how to calculate averages for scripting

I have some sar data which looks like this:

c39t1d1 10.1
c39t1d1 10.7
c39t1d1 11.0
c39t1d4 10.6
c39t1d4 10.8
c39t1d7 11.1
c39t1d7 11.4
c39t1d7 11.5
c39t1d7 16.3
c40t1d3 10.0
c40t1d3 10.1
c40t1d3 10.2
c40t1d3 10.2
c40t1d3 10.3
c40t1d3 10.1

I am not able to figure out how to calculate averages for each cXtXdX. Can somebody help a
newbie?
5 REPLIES 5
Dennis Handly
Acclaimed Contributor
Solution

Re: Need to learn how to calculate averages for scripting

If they are not sorted, you'll need to sort the input:
sort sar_data | awk '
BEGIN { getline; disk=$1; sum=$2; count=1 }
{
if ($1 == disk) {
sum += $2
++count
} else {
print disk, sum / count
disk=$1; sum=$2; count=1
}
}
END { print disk, sum / count } '
Wilson David
New Member

Re: Need to learn how to calculate averages for scripting

Perfect !! It solves a big headache for me. Thank you. Assigning 10 points.
Suraj K Sankari
Honored Contributor

Re: Need to learn how to calculate averages for scripting

Hi,

If you want to take the average of all data
so here is the solution:

awk '{ print $2}'tmp1.out
ln=`wc -l tmp1.out| awk '{print $1}'`
if test $ln -ne 0
then
tot=0
for i in `cat tmp1.out`
do
tot=`echo $tot + $i | bc -l`
done
avg=`echo $tot / $ln | bc -l`
fi
printf "SAR : %.2f\n" $avg
rm tmp1.out

Suraj
Dennis Handly
Acclaimed Contributor

Re: Need to learn how to calculate averages for scripting

>Suraj: If you want to take the average of all data

awk handles that too:
awk '
{
sum += $2
}
END { print sum / NR } ' sar_data
Suraj K Sankari
Honored Contributor

Re: Need to learn how to calculate averages for scripting

Hi Dennis,

Really it is a nice code.

Suraj