## Monday, February 26, 2007

### Sum of all digits of a number: BASH beginner

Here is my trick for the same.

\$ echo "12334"
12334
\$ echo "12334" | sed 's/[0-9]/ + &/g' ##mind the spaces before and after +
+ 1 + 2 + 3 + 3 + 4
\$ echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g' ## Space bet ^ and +
1 + 2 + 3 + 3 + 4
\$ expr `echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g'`
13

And this is the traditional script for the same.

#!/bin/sh
#Sum of all digits in a number

num=12334
tot=0
mod=0
echo "Number= \$num"
while [ \$num -gt 0 ]
do
mod=`expr \$num % 10`
tot=`expr \$tot + \$mod`
num=`expr \$num / 10`
done
echo "Sum= \$tot"

\$ ./sumofdigits.sh
Number= 12334
Sum= 13

Valpskott said...

Oh, thank you thank you, thank you!

expr `echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g'`

It was just what I was looking for, quite creative of you :)

Valpskott said...

Quite creative of you! Just the function I was looking for.

Valpskott said...

Oh, thank you thank you, thank you!

expr `echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g'`

It was just what I was looking for, quite creative of you :)