So far I have this script:
#!/bin/sh
echo type in some numbers:
read input
From here on I'm stuck. Let's say input=30790148
. What I want to do is add all of those integers up to get 3+0+7+9+0+1+4+8=32. How can I accomplish this?
So far I have this script:
#!/bin/sh
echo type in some numbers:
read input
From here on I'm stuck. Let's say input=30790148
. What I want to do is add all of those integers up to get 3+0+7+9+0+1+4+8=32. How can I accomplish this?
Another way not using external tools:
read -p "Type some number: " num
for((i=0;i<${#num};i++)); do ((sum+=${num:i:1})); done
echo "$sum"
There are two core utilities, fold
and paste
, which you can use here (illustrated for input=12345
):
fold -w1 <<< $input | paste -sd+ - | bc
fold -w1
wraps the input line to a width of 1 character:
$ fold -w1 <<< $input
1
2
3
4
5
paste -sd+ -
merges the input sequentially (-s
), i.e., into a single line, with a +
delimiter (-d+
), reading from standard input (the final -
; optional for GNU paste
):
$ fold -w1 <<< $input | paste -sd+ -
1+2+3+4+5
bc
then calculates the sum:
$ fold -w1 <<< $input | paste -sd+ - | bc
15
This one using sed
and bc
echo "12345" | sed -e 's/\(.\)/\1\+0/g' | bc
It's a bit hackish though since the +0
is not intuitive
Edit: Using &
from @PaulHodges' answer, this would shorten to:
echo "12345" | sed 's/./&+0/g' | bc
This awk one-liner may help you:
awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' FS="" <<< yourString
for example:
kent$ awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' FS=""<<< "123456789"
45
With sed
and bc
-
input=30790148; echo $input | sed 's/[0-9]/&+/g; s/$/0/;' | bc
If you don't have GNU sed
you might need to line break the commands instead of using a semicolon.
input=30790148;
echo $input |
sed '
s/[0-9]/&+/g
s/$/0/
' | bc