Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split each element of an array in zsh?

Tags:

zsh

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?

like image 925
Dominic Mitchell Avatar asked Dec 06 '11 22:12

Dominic Mitchell


1 Answers

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 x is an array, you shouldn't forget the [@], i.e. print ${(s,:,)x[@]}; thus your code becomes print -l ${(s,:,)x[@]}; but the solution is still another step:

> 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)

like image 118
Tom Regner Avatar answered Oct 12 '22 01:10

Tom Regner