Operating System - HP-UX
1745924 Members
4183 Online
108723 Solutions
New Discussion юеВ

Re: about the shell script

 
juno2
Super Advisor

about the shell script

I have a text file in shell , how to calculate the average of the it.

#vi abc.txt

10
20
30
40

I want to have the result 25 (100/4) , can suggest how to write the script ? thx.

 

 

P.S. This thread has been moved from HP-UX > System Administration to HP-UX > languages. - Hp ForumModerator

8 REPLIES 8
Graham Cameron_1
Honored Contributor

Re: about the shell script

So long as there are no blank lines in abc.txt, this will work:

cat abc.txt|awk '
{total+=$1}
END {printf "Average = %f\n", total/NR}
'

-- Graham
Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done.
TSaliba
Trusted Contributor

Re: about the shell script

hi
you can try the following:

sum=0
avr=0
for i in `cat abc.txt`
do
sum=`expr $sum + $i`
done
avr=`expr $sum / 4`

echo $avr


NB: use the right single quote "`" NOT "'"
jj
James Specht
Trusted Contributor

Re: about the shell script

#!/usr/bin/sh
lines=0
total=0
avg=0
cat abc.txt|while read LINE
do
lines=$(expr $lines + 1)
total=$(expr $total + $LINE)
done
avg=$(expr $total / $lines)
echo "Total : "$total
echo "Records: "$lines
echo "Average: "$avg

--Jim
"Everyone can be taught to sculpt: Michelangelo would have had to be taught how not to. So it is with the great programmers."
blal
Frequent Advisor

Re: about the shell script

Hi

Try this

cat abc.txt |grep "^$" |awk '{a+=$NF} END {print a/NR}'


This will give u avg of n numbers.
grep "^$" is used to filter blank lines if
any otherwise which will be also counted as NR.(number of records).

check it out.
bye
baiju.
Live and let live.
Jean-Louis Phelix
Honored Contributor

Re: about the shell script

Hi,

awk solution seems to be the simpliest one ... but just for your information, doing arithmetic operation is also simple in shell :

#!/usr/bin/sh
typeset -i TOT VAR NB
cat abc.txt | while read VAR
do
((TOT=TOT+VAR))
((NB=NB+1))
done
print $((TOT/NB))

Regards.
It works for me (┬й Bill McNAMARA ...)
juno2
Super Advisor

Re: about the shell script

thx reply, i hv another question , how to find the highest one ? ( the result should be 40) thx in advance .
Elmar P. Kolkman
Honored Contributor

Re: about the shell script

Quite simple...

awk 'BEGIN {max=0;total=0}
{ total += $1; if (max < $1) {max=$1}}
END {printf {"Average: %d \t Maximum: %d\n",total/NR,max);}'
Every problem has at least one solution. Only some solutions are harder to find.
Jean-Louis Phelix
Honored Contributor

Re: about the shell script

Or ...

#!/usr/bin/sh
typeset -i TOT VAR NB MAX
cat a | while read VAR
do
((TOT=TOT+VAR))
((NB=NB+1))
[[ VAR -gt MAX ]] && ((MAX=VAR))
done
print "Average : $((TOT/NB)) Max : $MAX"

Regards.
It works for me (┬й Bill McNAMARA ...)