Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering zsh array by wildcard

Tags:

zsh

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.

like image 491
user1934428 Avatar asked Jan 26 '17 11:01

user1934428


1 Answers

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

like image 94
Adaephon Avatar answered Oct 03 '22 03:10

Adaephon