How to split each element of an array in zsh?

If I have an array:

x=( a:1 b:2 c:3 ) 

How can I split each element of an array into a colon? I am trying to do this to form an associative array.

I tried several variations of this, but no one works:

 print -l ${(s,:,)x} 

Is it possible? If so, what am I missing?

+4
source share
2 answers

Well - further thinking drew me to this solution, which probably could be applied to the problem behind the question: Loop through 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 

Hope more helpful than first answer (s) :-)

Since x is an array, you should not forget [@] , i.e. print ${(s,:,)x[@]} ; this way your code becomes print -l ${(s,:,)x[@]} ; but the solution remains another step:

 > typeset -A z > x="a:1 b:2 c:3" > z=($(echo ${(s,:,)x})) > echo $z[a] 1 

Assigning an associative array is done with the output of the echo statement.

To clarify 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: translated thoughts midwriting: -D should now make more sense) (edit 2: striked brainf * rt - the similarities between zsh and bash are not as great as I assumed)

+3
source

typeset -A x will make x an associative array

 $ typeset -A x $ x=( a 1 b 2 c 3 ) $ echo $x[a] 1 $ echo $x[c] 3 $ x[d]=5 $ echo $x[d] 5 

But I don't know how to colonize if you need to start with the line "a: 1 b: 2 c: 3".

+2
source

Source: https://habr.com/ru/post/1385011/


All Articles