Operating System - HP-UX
1827283 Members
3261 Online
109717 Solutions
New Discussion

Adding up numbers in a file

 
SOLVED
Go to solution
Ferdie Castro
Advisor

Adding up numbers in a file

Hi just wanna ask how to develop a script. I have a file abc -- each lines contain numbers some decimals. I was having problem in adding up all the numbers because of this decimal thing. thanks
5 REPLIES 5
Michael Steele_2
Honored Contributor

Re: Adding up numbers in a file

Regarding "...this decimal thing..."

Why don't you use the programming languague that Unix was written in? 'C'?

Here's someones C program:

http://forums1.itrc.hp.com/service/forums/parseCurl.do?CURL=%2Fcm%2FQuestionAnswer%2F1%2C%2C0xa16a46ff9277d511abcd0090277a778c%2C00.html&admit=716493758+1066359015637+28353475


Integer addition :

x=$(($x+1))
Support Fatherhood - Stop Family Law
curt larson_1
Honored Contributor
Solution

Re: Adding up numbers in a file

use a shell that supports decimal numbers
#!/usr/dt/bin/dtksh
typeset -F total=0

cat yourfile |
while read number
total=$(( $total + $number ))
done
print $total

use a program that supports decimal numbers
#!/usr/bin/ksh

cat yourfile |
awk '{
total += $1;
} END {printf("%f\n",total)}'

or bc, perl, write your own
Mark Grant
Honored Contributor

Re: Adding up numbers in a file

Or use bc

#/usr/bin/sh

bc |&
TOTAL=0
while read num
do
print -p "$TOTAL + $num"
read -p TOTAL
done < myfile

echo $TOTAL
Never preceed any demonstration with anything more predictive than "watch this"
Graham Cameron_1
Honored Contributor

Re: Adding up numbers in a file

Or use awk.
Don't know how many cols your input file has, but assuming each line has 3 cols, each line of which you want totalling, then use:
--
cat yourfile|awk '
{tot1+=$1;tot2+=$2;tot3+=$3}
END {printf "Totals: %f, %f, %f\n", tot1, tot2, tot3}
'
--
This can be extended to the general case.
-- 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.
Martha Mueller
Super Advisor

Re: Adding up numbers in a file

I think Mark needs to add:

print -p scale = 2

to get 2 places to the right of the decimal point.