2

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?

3
  • str_split to do this Commented Nov 11, 2014 at 19:48
  • 2
    @Kisaragi, did you notice the "bash" tag? Commented Nov 11, 2014 at 20:29
  • Wasn't there before, so no. Commented Nov 11, 2014 at 22:02

4 Answers 4

5

What I would do in pure and parameter expansions:

number=5684398
len=${#number}
for ((i=0; i<len; i++)); do arr[$i]=${number:$i:1}; done 
Sign up to request clarification or add additional context in comments.

1 Comment

Or even better: arr=(); while [[ $number ]]; do arr+=( "${number::1}" ); number=${number:1}; done.
3

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

1 Comment

I know, but i was still in the 5 minutes lock after opening a question :)
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.