如何在不迭代元素的情况下检查字符串是否在数组中?

Hom*_*lli 12 bash

有没有办法检查一个字符串数组中是否存在字符串 - 没有遍历数组?

例如,给定下面的脚本,我如何正确地实现它来测试存储在变量$ test中的值是否存在于$ array中?

array=('hello' 'world' 'my' 'name' 'is' 'perseus')

#pseudo code
$test='henry'
if [$array[$test]]
   then
      do something
   else
      something else
fi
Run Code Online (Sandbox Code Playgroud)

注意

我正在使用bash 4.1.5

Cha*_*ffy 12

使用bash 4,您可以做的最接近的事情是使用关联数组.

declare -A map
for name in hello world my name is perseus; do
  map["$name"]=1
done
Run Code Online (Sandbox Code Playgroud)

...... 完全相同的事情:

declare -A map=( [hello]=1 [my]=1 [name]=1 [is]=1 [perseus]=1 )
Run Code Online (Sandbox Code Playgroud)

...其次是:

tgt=henry
if [[ ${map["$tgt"]} ]] ; then
  : found
fi
Run Code Online (Sandbox Code Playgroud)


Tod*_*obs 5

技术上总是迭代,但它可以降级到shell的底层数组代码.Shell扩展提供了一个隐藏实现细节的抽象,并避免了在shell脚本中显式循环的必要性.

使用fgrep可以更轻松地处理这个用例的单词边界,fgrep具有处理全字固定字符串的内置工具.正则表达式匹配更难以正确,但下面的示例适用于提供的语料库.

外部Grep过程

array=('hello' 'world' 'my' 'name' 'is' 'perseus')
word="world"
if echo "${array[@]}" | fgrep --word-regexp "$word"; then
    : # do something
fi
Run Code Online (Sandbox Code Playgroud)

Bash正则表达式测试

array=('hello' 'world' 'my' 'name' 'is' 'perseus')
word="world"
if [[ "${array[*]}" =~ (^|[^[:alpha:]])$word([^[:alpha:]]|$) ]]; then
    : # do something
fi
Run Code Online (Sandbox Code Playgroud)