Sum of digits using bash and sed


/ Published in: Bash
Save to your folder(s)

Sum of digits using bash and sed


Copy this code and paste it in your HTML
  1. #!/bin/sh
  2. #Sum of all digits in a number
  3.  
  4. num=12334
  5. tot=0
  6. mod=0
  7. echo "Number = $num"
  8. while [ $num -gt 0 ]
  9. do
  10. mod=$(expr $num % 10)
  11. tot=$(expr $tot + $mod)
  12. num=$(expr $num / 10)
  13. done
  14. echo "Sum= $tot"
  15.  
  16. $ ./sumofdig.sh
  17. Number = 12334
  18. Sum= 13
  19.  
  20. Another alternative using sed:
  21.  
  22. $ expr $(echo "12334" | sed -e 's/[0-9]/ + &/g' -e 's/^ +//g')
  23. 13
  24.  
  25. Breakdown steps:
  26.  
  27. $ echo "12334"
  28. 12334
  29.  
  30. $ echo "12334" | sed 's/[0-9]/ + &/g'
  31. + 1 + 2 + 3 + 3 + 4
  32.  
  33. $ echo "12334" | sed -e 's/[0-9]/ + &/g' -e 's/^ +//g'
  34. 1 + 2 + 3 + 3 + 4
  35.  
  36. $ expr $(echo "12334" | sed -e 's/[0-9]/ + &/g' -e 's/^ +//g')
  37. 13

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.