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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding numbers in a string

Status
Not open for further replies.

alqsp

Programmer
Dec 12, 2001
9
AU
This should be easy! I need to add the numbers in a string.

e.g
VALUE=138
I need the sum of 1+3+8.

I imagine something like"
i=0
for [ number of chars in string ]
do
TOTAL=`expr $TOTAL + $VALUE`
increment i
done

This example will give a TOTAL of 13.

I then need to identify the left-most value in this number, in this case 1.

Idea's on the best way to do this?
 
Hi,

I can think of a script like this -
--------------start add_digits.sh --------------------------
#! /bin/ksh

if [ $# -ne 1 ]
then
echo "Usage: add_digits number"
exit
fi

#Number=first parameter
#expr will filter out spaces and raise an error if non-numeric characters are present

NUM=`expr $1`

#Length of Number
LEN=`echo $NUM | wc -m`

#Subtract 1 for newline
LEN=`expr $LEN - 1`

SUM=0

echo NUM=$NUM
echo LEN=$LEN
echo SUM=$SUM

i=0

while TRUE=TRUE
do
i=`expr $i + 1`

subNUM=`echo $NUM | cut -c $i`

echo subNUM=$subNUM

SUM=`expr $SUM + $subNUM`

echo SUM=$SUM

if [ $i -eq $LEN ]
then
break
fi
done

echo Final SUM=$SUM
-----------------end add_digits.sh -------------------------
While this may not be the most elegant solution, it works never the less. To get the first character of the resulting sum -
$echo $SUM | cut -c 1

Hope you find it useful.
 
This is probably not the most elegant solution but it works ;-)

#!/bin/ksh

YOUR_NUM=59999991234
NUM=$YOUR_NUM
Y=${#NUM}
i=1

while [[ i -le $Y ]]
do
((DIFF=$Y - $i))
typeset -L1 NUM
typeset -R$DIFF YOUR_NUM
if [[ i -eq 1 ]]
then
echo "FIRST NUMBER is $NUM"
fi
((i=i+1))
SUM1=$NUM
if [[ i -gt 1 ]]
then
((SUM=$SUM+$SUM1))
if [[ DIFF -eq 0 ]]
then
echo "SUM is $SUM"
fi
fi
NUM=$YOUR_NUM
done

Hope that helps!

mrjazz [pc2]
 
If this script was called add.sh just pass the number to it..

#./add.sh 138
12
#


NUM=$1
CHARS=`echo $NUM | wc -c`
x=1
VAL=0
while [ $x -lt $CHARS ] ; do
DIGIT=`echo $NUM | cut -c $x`
VAL=`expr $VAL + $DIGIT`
x=`expr $x + 1`
done
echo $VAL
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top