user1934428
user1934428

Reputation: 22227

Filtering zsh array by wildcard

Given a Zsh array myarray, I can make out of it a subset array

set -A subarray
for el in $myarray
do 
  if [[ $el =~ *x*y* ]]
  then
    subarray+=($el)
  fi
done

which, in this example, contains all elements from myarray which have somewhere an x and an y, in that order.

Question:

Given the plethora of array operations available in zsh, is there an easier way to achieve this? I checked the man page and the zsh-lovers page, but couldn't find anything suitable.

Upvotes: 10

Views: 1706

Answers (1)

Adaephon
Adaephon

Reputation: 18349

This should do the trick

subarray=(${(M)myarray:#*x*y*z})

You can find the explanation in the section about Parameter Expansion in the zsh manpage. It is a bit hidden as ${name:#pattern} without the flag (M) does the opposite of what you want:

${name:#pattern}

If the pattern matches the value of name, then substitute the empty string; otherwise, just substitute the value of name. If name is an array the matching array elements are removed (use the (M) flag to remove the non-matched elements).

Upvotes: 14

Related Questions