Filtering zsh array by wildcard

谁说胖子不能爱 提交于 2020-08-04 15:29:47

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/41872135/filtering-zsh-array-by-wildcard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!