zsh:检查字符串是否在数组中

时间:2011-03-05 11:57:56

标签: arrays zsh

E.g。

foo=(a b c)

现在,如果b中有$foo,我该如何轻松检查?

3 个答案:

答案 0 :(得分:25)

您可以使用反向订阅:

pax$ foo=(a b c)

pax$ if [[ ${foo[(r)b]} == b ]] ; then ; echo yes ; else ; echo no ; fi
yes

pax$ if [[ ${foo[(r)x]} == x ]] ; then ; echo yes ; else ; echo no ; fi
no

您会在man zshparam下的Subscript Flags下找到数据(至少在zsh 4.3.10Ubuntu 10.10下)。


或者(感谢geekosaur),您可以使用:

pax$ if [[ ${foo[(i)b]} -le ${#foo} ]] ; then ; echo yes ; else ; echo no ; fi

您只需执行以下操作即可看到您从这两个表达式中获得的内容:

pax$ echo ${foo[(i)a]} ${#foo}
1 3

pax$ echo ${foo[(i)b]} ${#foo}
2 3

pax$ echo ${foo[(i)c]} ${#foo}
3 3

pax$ echo ${foo[(i)d]} ${#foo}
4 3

答案 1 :(得分:18)

(( ${foo[(I)b]} )) \
  && echo "it's in" \
  || echo "it's somewhere else maybe"

答案 2 :(得分:4)

如果找到匹配项,反向下标将始终返回一些内容,如果未找到匹配项,则不会返回任何内容。我们可以用它来简化答案。

$ foo=(a b c)

$ [[ -n "${foo[(r)b]}" ]] && echo 'b was found.' || echo 'b was not found.'
b was found.

$ [[ -n "${foo[(r)d]}" ]] && echo 'd was found.' || echo 'd was not found.'
d was not found.