Reputation: 1523
I have a number, say
number=5684398
and I want to store its digits into the fields of an array coolarray
as follows:
coolarray[0]=5
coolarray[1]=6
coolarray[2]=8
coolarray[3]=4
coolarray[4]=3
coolarray[5]=9
coolarray[6]=8
How can I proceed?
Upvotes: 2
Views: 694
Reputation: 1709
How about this simple one-liner:
number=5684398
unset coolarray; while read -n1 a; do coolarray+=($a); done <<< $number
echo ${coolarray[@]}
5 6 8 4 3 9 8
Explanation: Bash build-in "read" can take one character at a time by using "n1". Array append structure +=() is used to buid the result. That "unset coolarray" is needed to avoid stacking up resulting array to previous array after each run time.
Upvotes: 0
Reputation: 247042
Using shell arithmetic:
$ for (( i=${#number}-1; i>=0; i-- )); do ary+=( $((number / 10**i % 10)) ); done
$ printf "%s\n" "${ary[@]}"
5
6
8
4
3
9
8
Upvotes: 0
Reputation: 185550
What I would do in pure bash and parameter expansions:
number=5684398
len=${#number}
for ((i=0; i<len; i++)); do arr[$i]=${number:$i:1}; done
Upvotes: 5
Reputation: 785651
You can use fold -w1
to break input string into each character:
number=5684398
coolarray=( $(fold -w1 <<< "$number") )
printf "%s\n" "${coolarray[@]}"
5
6
8
4
3
9
8
Upvotes: 3