-   Programming (
-   -   calculating average of a column of numbers in bash (

hta1984 12-13-2006 08:44 AM

calculating average of a column of numbers in bash

while read myline
    if [ $i -eq 1 ]
        echo "Report Date: $(cut -d" " -f4 ornek2-c.txt)" > output.txt
    elif [ $i -gt 3 ]
        echo $myline > temp.txt
        proc=$(cut -d" " -f3 temp.txt)
        echo $proc > temp.txt
        cat temp.txt >> temp2.txt
    i=$(expr $i + 1)
done <ornek2-c.txt

index=$(expr $i - 4)
cat temp2.txt | awk '{ sum+=$1 } END {print sum}'
average=$(echo "scale=4; $sum/$index"|bc)
echo $average
exit 0


the output after execution(./

(standard_in) 1: parse error

i created ornek2-c.txt file with "sar -c -f > ornek2-c.txt" command.i'm trying to find the average value of the proc/s column in ornek2-c.txt.

Thanks in advance.

makyo 12-13-2006 09:34 AM


The variable "sum" is not defined in:

average=$(echo "scale=4; $sum/$index"|bc)
You could modify the previous line to:

sum=$( cat temp2.txt | awk '{ sum+=$1 } END {print sum}' )
which would then produce:

I removed the temp files before running and added a newline at the end of the last line of the input text file. If the newline is present, the script produces:

... cheers, makyo

nx5000 12-13-2006 09:57 AM

For security reasons (and also because its simpler) you should use mktemp

makyo 12-13-2006 11:12 AM

Hi, nx5000.

Good point, thanks. Yes, security issues are always important to keep in mind and mktemp is useful in that regard.

In this case, however, the reason for removing the files was more operational. The files were local, the script was appending to at least one file, and the results would be calculated incorrectly from the accumulation rather than the single dataset.

While I like the man page for mktemp because of the examples, I would say that one can as easily create filenames by using the $RANDOM value in bash, although one might still want to address the permissions issue. From my perspective the removal of temporary files, say with trap is at least as important as a random name. I don't reboot systems that often, I don't like the clutter in /tmp or elsewhere, and I also don't want to worry about accumulations as above.

Still, consistent use of mktemp or similar facilities can help with security particularly on shared systems ... cheers, makyo

hta1984 12-13-2006 11:58 AM

thank you very much

All times are GMT -5. The time now is 03:31 AM.