If I have an array:
x=( a:1 b:2 c:3 )
How can I split each element of the array on the colon? I'm trying to do this in order to form an associative array.
I've tried several variations on this, but none seem to work:
print -l ${(s,:,)x}
Is this possible? If so, what am I missing?
Ok - further thinking got me to this solution, that might probably be applicable to the problem behind the question asked:
Loop through the array x
!
> x=(a:1 b:2 c:3)
> typeset -A z
> for i in $x; do z+=(${(s,:,)i}); done
> echo $z
1 2 3
> echo ${z[a]}
1
I hope that's more helpful than the first answer(s) :-)
Since the solution is still another step:x
is an array, you shouldn't forget the [@]
, i.e. print ${(s,:,)x[@]}
; thus your code becomes print -l ${(s,:,)x[@]}
; but
> typeset -A z
> x="a:1 b:2 c:3"
> z=($(echo ${(s,:,)x}))
> echo $z[a]
1
The assignement to the associative array is done with the output of the echo statement.
To clarify further and include your original example x
:
> typeset -A z
> x=(a:1 b:2 c:3)
> z=($(echo ${(s,:,)x[@]}))
> echo ${z[a]}
1
> echo ${z[b]}
2
(edit: switched thoughts midwriting :-D, should make more sense now) (edit 2: striked brainf*rt - similarities between zsh and bash aren't as broad as I assumed)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With