Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple small shell script to compute averages

Can anyone tell me what I'm doing wrong here?

#!/bin/sh

if [ $# = 0 ]
then
    echo "Usage: $0 <filename>"
    exit 1
fi

sum=0
count=0

while [ $0 != 0 ]
do
        sum="$sum"+"$2"
        count="$count"+ 1

done
if [ "$count" != 0 ]
then
        avg="$sum"/"$count"
        printf "Sum= $sum \n Count= $count  \n Avg= $avg"
        exit 0
else
        printf "Sum= $sum \n Count= $count  \n Avg= undefined"
        exit 0
fi
exit 1

Here's the output when I try to test the code:

./average

sum: =: No such file or directory
sum: 0: No such file or directory
./average: 11: count: not found
[: 18: !=0: unexpected operator
./average: 25: Syntax error: Unterminated quoted string

Basically if I had a file that looked something like this:

FirstPerson 23 

SecondPerson 36

ThirdPerson 22

I want to be able to read that into my program and have it output:

Sum = FirstPerson+SecondPerson+ThirdPerson

Count = NumberofPeople

Average = Sum/Count
like image 772
에이바 Avatar asked Nov 27 '22 08:11

에이바


2 Answers

 awk '{sum+=$2}END{printf "Sum=%d\nCount=%d\nAve=%.2f\n",sum,NR,sum/NR}' ave.txt

First off, Bash cannot do integer division, you will either need to pipe the math to a tool like 'bc' or just use awk to do it all as it's quite powerful; after all, that entire script of yours was turned into a 1-liner.

Sample Input

$ cat ave.txt
FirstPerson 23
SecondPerson 36
ThirdPerson 22

Result

Sum=81
Count=3
Ave=27.00
like image 167
SiegeX Avatar answered Dec 11 '22 11:12

SiegeX


I don't know about your shell script, but I know you should be using the right tool for the job. That tool is AWK. It was designed specifically for this task and, if you are using UNIX (or Linux, or Mac OS X or whatever) you have it installed. This is the one-liner:

awk '{ sum+=$2; count+=1 } END {print "Sum =",sum; print "Count =",count; print "Average= ",sum/count}' test2.dat 

Read the guide for AWK. The philosophy of UNIX is DO NOT REINVENT THE WHEEL. Use the right tools, buddy.

Good luck,

like image 27
Escualo Avatar answered Dec 11 '22 11:12

Escualo