Return to Snippet

Revision: 10414
at December 28, 2008 10:29 by jaduks


Updated Code
#!/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"

$ ./sumofdig.sh
Number = 12334
Sum= 13

Another alternative using sed: 

$ expr $(echo "12334" | sed -e 's/[0-9]/ + &/g' -e 's/^ +//g')
13

Breakdown steps: 

$ echo "12334"
12334

$ echo "12334" | sed 's/[0-9]/ + &/g'
 + 1 + 2 + 3 + 3 + 4

$ echo "12334" | sed -e 's/[0-9]/ + &/g' -e 's/^ +//g'
 1 + 2 + 3 + 3 + 4

$ expr $(echo "12334" | sed -e 's/[0-9]/ + &/g' -e 's/^ +//g')
13

Revision: 10413
at December 28, 2008 01:44 by jaduks


Updated Code
#!/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"

$ ./sumofdig.sh
Number = 12334
Sum= 13

Another alternative using sed: 

$ expr $(echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g')
13

Revision: 10412
at December 28, 2008 01:39 by jaduks


Initial Code
#!/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"

$ ./sumofdig.sh
Number = 12334
Sum= 13

Another alternative using sed: 

$ expr $(echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g')
13

Initial URL
http://unstableme.blogspot.com/2007/02/sum-of-all-digits-of-number.html

Initial Description
Sum of digits using bash and sed

Initial Title
Sum of digits using bash and sed

Initial Tags
Bash

Initial Language
Bash