Pablo Lalloni
Pablo Lalloni

Reputation: 2755

How can zsh array elements be transformed in a single expansion?

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

Upvotes: 1

Views: 971

Answers (1)

hchbaw
hchbaw

Reputation: 5319

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

Upvotes: 2

Related Questions