/ Published in: Bash

Sum of digits using bash and sed
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/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
URL: http://unstableme.blogspot.com/2007/02/sum-of-all-digits-of-number.html
Comments
