Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sum up numbers in a file? 1

Status
Not open for further replies.

jouell

MIS
Nov 19, 2002
304
US
Can someone point me in the right direction (the search is not working now).

If I have a file w/10 number in it, how can I sum them up in ksh? Is there a better unix util to do it other than ksh?

thanks!
-john
 
Code:
#!/bin/ksh

i=0
while read line
do
        ((i+=line))
done < x
print $i

where x is the file that contains the numbers:
1
2
3
4
5
6
7
8
9
10
 
what's your sample file?

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Awesome and so timely!!
THANKS 11011110000 !!
-John
 
If you are not using whole numbers, I would suggest using ksh93.

Code:
#!/usr/dt/bin/dtksh

float i=0
while read line
do
        float a=$line
        ((i+=a))
done < x
print $i

If your numbers file contained:
1.23
2.374
3.833
4.435
5.34477
6.0432573
7
8.2
9
10.26262624
 
or:

(tr '\n' '+' < file ; echo '0') | bc

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Another way:
tot=$(awk '{t+=$1}END{print t}' /path/to/file)

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top