1

Say you have a zsh array like:

a=("x y" "v w")

I want to take the first word of every element, say:

b=()
for e in $a; {
  b=($b $e[(w)0])
}

So now I have what I need in b:

$ print ${(qq)b}
'x' 'v'

Is there a way to do this in a single expansion expression? (i.e. not needing a for loop for processing each array element and accumulating the result in a new array).

Pablo Lalloni
  • 2,615
  • 19
  • 20

1 Answers1

2

It could be possible to take the word by removing from the first occurrence of a white space to the end in each element of the array like this:

$ print ${(qq)a%% *}
'x' 'v'

It coulde be noted that the%% expression (and some others) could be used for array elements:

In the following expressions, when name is an array and the substitution is not quoted, or if the ‘(@)’ flag or the name[@] syntax is used, matching and replacement is performed on each array element separately.
...

${name%pattern}
${name%%pattern}

If the pattern matches the end of the value of name, then substitute the value of name with the matched portion deleted; otherwise, just substitute the value of name. In the first form, the smallest matching pattern is preferred; in the second form, the largest matching pattern is preferred.

-- zshexpn(1): Expansion, Parameter Expansion

hchbaw
  • 4,894
  • 18
  • 16