Ghost
Ghost

Reputation: 1523

Pass digits of a numeric string to an array in bash

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

Answers (4)

ajaaskel
ajaaskel

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

glenn jackman
glenn jackman

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

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185550

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 

Upvotes: 5

anubhava
anubhava

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

Related Questions