Finding an average


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Finding an average
# 1  
Old 10-07-2013
Finding an average

Basically, I need to find average of numbers which are given like:
sh average file1 file (in files can be more than one number)
->10
sh average 5 7
->6
sh average /users/file
->5
echo 5 7 | sh average
6
So basically i wrote my code but it gives me error... I am pretty sure it has to work for first two cases at least.... But I stucked with my error messages ;(
this is my code:

Code:
sum=0
n=0
for i in $*
do
    if [ -f $i ]
    then
        while read line
        do

           n=` expr $n + 1 `
           sum=` expr $sum + $line `
                         done < $i

        else
           sum=` expr $sum + $i `
           n=` expr $n + 1 `
           fi


         done

          average=` expr $sum / $n `
          echo $average

# 2  
Old 10-07-2013
Your requirement is not quite clear.
The following reads numbers of files from arguments, or from stdin if no arguments are provided.
The numbers in files or stdin can be placed in columns or rows or both
Code:
set -f # no wildcard globbing
sum=0
n=0

from_stdin() {
while read line
do
    set -- $line
    for i
    do
       sum=` expr $sum + $i `
       n=` expr $n + 1 `
    done
done
}

if [ -z "$1" ]
then
   from_stdin
else
    for i
    do
        if [ -f "$i" ]
        then
            from_stdin < "$i"
        else
            sum=` expr $sum + $i `
            n=` expr $n + 1 `
        fi
    done
fi

if [ $n -gt 0 ]
then
    average=` expr $sum / $n `
    echo $average
fi


Last edited by MadeInGermany; 10-07-2013 at 04:17 PM.. Reason: quoting to allow file name with spaces
This User Gave Thanks to MadeInGermany For This Post:
# 3  
Old 10-07-2013
Quote:
Originally Posted by Manu1234567
Basically, I need to find average of numbers which are given like:
sh average file1 file (in files can be more than one number)
->10
sh average 5 7
->6
sh average /users/file
->5
echo 5 7 | sh average
6
So basically i wrote my code but it gives me error... I am pretty sure it has to work for first two cases at least.... But I stucked with my error messages ;(
this is my code:

Code:
sum=0
n=0
for i in $*
do
    if [ -f $i ]
    then
        while read line
        do

           n=` expr $n + 1 `
           sum=` expr $sum + $line `
                         done < $i

        else
           sum=` expr $sum + $i `
           n=` expr $n + 1 `
           fi


         done

          average=` expr $sum / $n `
          echo $average

Code:
you have to use bc and you also need to check argument exist or not

try

Code:
#!/bin/ksh

check(){
    if [ -z "$1" ];then echo "No user input exiting..";exit;fi
       }

check $1

sum=0
n=0
for i in $*
do
    if [ -f $i ]
    then
        while read line
        do
           n=` expr $n + 1 `
           sum=` expr $sum + $line `
        done < $i

        else
           sum=` expr $sum + $i `
           n=` expr $n + 1 `
           fi
done
    average=$(echo "scale=3; $sum/$n" | bc -l )
    echo $average


Last edited by Akshay Hegde; 10-07-2013 at 04:42 PM..
This User Gave Thanks to Akshay Hegde For This Post:
# 4  
Old 10-07-2013
Quote:
Originally Posted by Akshay Hegde
Code:
you have to use bc and you also need to check argument exist or not

try

Code:
#!/bin/ksh

check(){
    if [ -z "$1" ];then echo "No user input exiting..";exit;fi
       }

check $1

sum=0
n=0
for i in $*
do
    if [ -f $i ]
    then
        while read line
        do
           n=` expr $n + 1 `
           sum=` expr $sum + $line `
        done < $i

        else
           sum=` expr $sum + $i `
           n=` expr $n + 1 `
           fi
done
    average=$(echo "scale=3; $sum/$n" | bc -l )
    echo $average

it is strange.....sometimes it gives me an error:
expr: syntax error
expr: syntax error
(standard_in) 1: parse error????
But sometimes it works fine O_o


My code is ok if file contains numbers in columns.... How to fix it in way that code works with files where numbers can be in rows as well, or both?
---------- Post updated at 08:29 PM ---------- Previous update was at 08:26 PM ----------

Quote:
Originally Posted by MadeInGermany
Your requirement is not quite clear.
The following reads numbers of files from arguments, or from stdin if no arguments are provided.
The numbers in files or stdin can be placed in columns or rows or both
Code:
set -f # no wildcard globbing
sum=0
n=0

from_stdin() {
while read line
do
    set -- $line
    for i
    do
       sum=` expr $sum + $i `
       n=` expr $n + 1 `
    done
done
}

if [ -z "$1" ]
then
   from_stdin
else
    for i
    do
        if [ -f "$i" ]
        then
            from_stdin < "$i"
        else
            sum=` expr $sum + $i `
            n=` expr $n + 1 `
        fi
    done
fi

if [ $n -gt 0 ]
then
    average=` expr $sum / $n `
    echo $average
fi

I tried with your changes but it gives me error like

expr: not a decimal number: 'doc1'
expr: syntax error??

Last edited by Manu1234567; 10-07-2013 at 09:53 PM..
# 5  
Old 10-07-2013
So, did you invoke your script with doc1 as an operand (when there is no file named doc1), or did you specify a file as an operand where the file exists and contains the word doc1 instead of just numbers?
# 6  
Old 10-07-2013
Quote:
Originally Posted by Don Cragun
So, did you invoke your script with doc1 as an operand (when there is no file named doc1), or did you specify a file as an operand where the file exists and contains the word doc1 instead of just numbers?
Thanks I found out what is wrong. But can you recommend smth with previous comment about how to modify code with file containing numbers in row also.....
# 7  
Old 10-07-2013
Of course I could. Depending on what shell you're using and what operating system you're using, the script you have is probably not only not working in some cases, but also very inefficient in the cases that are working. So, to provide you with a reasonable, working solution, how about answering some questions first:
  1. What shell are you using?
  2. If you aren't using the Korn shell, is it OK to use the Korn shell instead of the shell you're using?
  3. Do you have access to a 1993 or later version of ksh?
  4. What operating system are you using?
  5. What is the name of your file that contains one or more rows with more than one number in a row?
  6. What is the actual contents of the file that contains more than one number in one or more rows?
  7. What happens when you use set -xvf instead of set -f to trace the commands your script is running (so you can actually see the expr command that is failing)?
  8. Show us some sample invocations of your script, the contents of any files named in those sample invocations, and the output that you expect from each of those sample invocations!
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Advanced & Expert Users

Want to get average value for each hour

I want to get CPU average value only (not required user CPU & memory) with each hours on individual date. The sample output is below | | | User |Memory| User | Date | Time |CPU %|CPU % | % |Mem % | 03/02/2015|00:00:00| 24.56| 20.66| 89.75| 63.48|... (13 Replies)
Discussion started by: Saravanan_0074
13 Replies

2. Shell Programming and Scripting

Finding minimum maximum and average

I am trying to find the minimum maximum and average from one file which has values Received message from https://www.demandmatrix.net/app/dm/xml] in milliseconds. Received message from https://www.demandmatrix.net/app/dm/xml] in milliseconds. Received message from... (5 Replies)
Discussion started by: aroragaurav.84
5 Replies

3. Shell Programming and Scripting

shell script for finding average runtime of other script

so I've made a shell script that downloads 6 files in succession from a given url, then deletes them. Now I want to time the script, and the average time it uses by running it ~100 times. My problem is tho, how do I store the time it takes for each run through of the script? I know time writes to... (3 Replies)
Discussion started by: navlelo
3 Replies

4. Shell Programming and Scripting

Perl- Finding average "frequency" of occurrence of duplicate lines

Hello, I am working with a perl script that tries to find the average "frequency" in which lines are duplicated. So far I've only managed to find the way to count how many times the lines are repeated, the code is as follows: perl -ae' my $filename= $ENV{'i'}; open (FILE, "$filename") or... (10 Replies)
Discussion started by: acsg
10 Replies

5. UNIX for Dummies Questions & Answers

Please Help me in my load average

Hello AlL,.. I want from experts to help me as my load average is increased and i dont know where is the problem !! this is my top result : root@a4s # top top - 11:30:38 up 40 min, 1 user, load average: 3.06, 2.49, 4.66 Mem: 8168788k total, 2889596k used, 5279192k free, 47792k... (3 Replies)
Discussion started by: black-code
3 Replies

6. UNIX for Dummies Questions & Answers

average value

If I have a file like this, could anyone please guide me how to find the average value in each metrix. The file has got about 130,000 metrixs. Grid-ref= 142, 235 178 182 203 240 273 295 289 293 283 262 201 176 167 187 187 246 260 282 299 312 293 276 230 191 169 ... (2 Replies)
Discussion started by: su_in99
2 Replies

7. Shell Programming and Scripting

finding duplicate files by size and finding pattern matching and its count

Hi, I have a challenging task,in which i have to find the duplicate files by its name and size,then i need to take anyone of the file.Then i need to open the file and find for more than one pattern and count of that pattern. Note:These are the samples of two files,but i can have more... (2 Replies)
Discussion started by: jerome Sukumar
2 Replies

8. UNIX for Dummies Questions & Answers

Load Average

Hello all, I have a question about load averages. I've read the man pages for the uptime and w command for two or three different flavors of Unix (Red Hat, Tru64, Solaris). All of them agree that in the output of the 2 aforementioned commands, you are given the load average for the box, but... (3 Replies)
Discussion started by: Heathe_Kyle
3 Replies

9. UNIX Desktop Questions & Answers

How to find no of occurances Finding average time?

Hi, I have MyLog.log file, and it contains "*** response Time 150", I want to develop Unix script like , 1. extract all such occurances in the MyLog.log file and 2. compute the average time taken I am new to Unix, any one can give any idea/sample code for this? Thanks in advance. (1 Reply)
Discussion started by: redlotus72
1 Replies

10. Programming

Finding Average for BST

Helo guys, this is not specifically a C programming problem for the unix platform, but a problem i came across in class: Find the average for a binary search tree: typedef Struct SNode { double value; SNode *leftChild; SNode *rightChild; } as SNode; /* * Solution 1 */ ... (2 Replies)
Discussion started by: heljy
2 Replies
Login or Register to Ask a Question