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"
${num:i:1}. Seems like a number splitter, shifting one decimal -1- to the right by adding one to each fixed position i$num is a "string", ${num:i:1} is bash's equivalent of num[i] in other languages.((sum+=${num:i:1}))$ in the arithmetic expansion (( expr )). From manual: ...shell variables may also be referenced by name without using the parameter expansion syntax.((sum+=${num:i})) without 1 will be a right shift by one reducing the array to the right.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
bc, but watch out with prepending zeroes to numbers; in some places, the number will suddenly be interpreted as octal.bc will interpret everything here as decimal. I was gunning for the shortest code possible e.g. sed 's/./&+0/g' | bc1+02+09+0. Since 09 is not a valid octal number, it would definitely error out.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
sed 's/./&+0/g' | bc. TIL of &, thank you.&, another tool in the toolbox.