通过通配符过滤 zsh 数组 [英] Filtering zsh array by wildcard

查看:10
本文介绍了通过通配符过滤 zsh 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 Zsh 数组 myarray,我可以把它做成一个子集数组

set -A 子数组对于 $myarray 中的 el做如果 [[ $el =~ *x*y* ]]然后子数组+=($el)菲完毕

在这个例子中,它包含来自 myarray 的所有元素,这些元素在某处有一个 x 和一个 y,按照这个顺序.>

问题:

鉴于 zsh 中有大量可用的数组操作,是否有更简单的方法来实现这一点?我检查了手册页和 zsh-lovers 页面,但找不到任何合适的.

解决方案

这应该可以解决问题

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

您可以在 zsh 手册页的 [关于参数扩展的部分] 中找到解释.它有点隐藏,因为 ${name:#pattern} 没有标志 (M) 与您想要的相反:

<块引用>

${name:#pattern}

如果patternname的值匹配,则替换为空字符串;否则,只需替换 name 的值.如果 name 是一个数组,则删除匹配的数组元素(使用 (M) 标志删除不匹配的元素).

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.

解决方案

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

这篇关于通过通配符过滤 zsh 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆