Re: easy way to add a bunch of numbers in a script

From: Aaron Morris (aaronmorris@MINDSPRING.COM)
Date: Sat Oct 19 2002 - 00:35:41 EDT


Korn shell in AIX (not sure about bourne shell or bash) have the ability
to do basic math.

-----------------
#!/usr/bin/ksh
TOTAL=0
NUMBERS=$(cat filename.txt)
for NUMBER in $NUMBERS; do {
TOTAL=$(($TOTAL + $NUMBER))
} done
echo $TOTAL
-----------------

$NUMBERS could also be

NUMBERS="1 2 3 4 10 55"

or

NUMBERS="1
2
3
4
10
55"

-Aaron Morris

Michelle DeVault wrote:
> Thanks, this was what I was looking for.
>
> --- Paul LaMadeleine <plamadeleine@LIGHTBRIDGE.COM>
> wrote:
>
>>I like doing it this way:
>>
>> Sum=`awk '{sum+=$1} END{print sum}' file`
>>
>>or in a stream by
>>
>> Sum=`generate stream | awk '{sum+=$1}
>>END{print sum}'`
>>
>>for example to get the size of all file in a
>>directory that begin with the
>>letter a:
>>
>> size=`ls -l a* | awk '{sum+=$5} END{print
>>sum}'
>>
>>Hope this helps,
>>
>> Paul
>>
>>At 12:31 PM 10/18/2002 -0700, you wrote:
>>
>>>I have a column of numbers (either in a variable or
>>>written to a file) that I need to total in a
>>
>>script.
>>
>>>What's the preferred way to do this?
>>>
>>>__________________________________________________
>>>Do you Yahoo!?
>>>Faith Hill - Exclusive Performances, Videos & More
>>>http://faith.yahoo.com
>>
>
>
> __________________________________________________
> Do you Yahoo!?
> Faith Hill - Exclusive Performances, Videos & More
> http://faith.yahoo.com
>



This archive was generated by hypermail 2.1.7 : Wed Apr 09 2008 - 22:16:16 EDT