Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 是否将字符串与数组中的所有元素进行比较?_Arrays_Bash_Grep - Fatal编程技术网

Arrays 是否将字符串与数组中的所有元素进行比较?

Arrays 是否将字符串与数组中的所有元素进行比较?,arrays,bash,grep,Arrays,Bash,Grep,我知道可能有一种方法可以做到这一点,但大多数方法都与我试图实现的目标相反。我想比较数组中的元素(来自“words”程序的英语词典单词),看看它们是否包含在字符串中的任何位置。例如,如果我输入123hello456,它将根据数组扫描我的字符串,并在该字符串中找到hello,即使它被数字包围 read -p "enter test string: " string array=(`cat /usr/share/dict/words`) if [[ "${array[*]}" == *"$string

我知道可能有一种方法可以做到这一点,但大多数方法都与我试图实现的目标相反。我想比较数组中的元素(来自“words”程序的英语词典单词),看看它们是否包含在字符串中的任何位置。例如,如果我输入123hello456,它将根据数组扫描我的字符串,并在该字符串中找到hello,即使它被数字包围

read -p "enter test string: " string
array=(`cat /usr/share/dict/words`)
if [[ "${array[*]}" == *"$string"* ]]; then
echo "there is a dictionary word in your string"
else
echo "no dictionary words contained within your string"
fi

一个简单的选择是使用
grep
,它允许您指定要匹配的多个模式,还可以使用固定字符串(而不是正则表达式)来避免这种开销

$ grep -F -f /usr/share/dict/words <<<'123hello456'
123hello456

请注意,如果您经常调用此函数,则效率不高,因为每次
grep
都必须重新加载整个
words
文件。根据你想完成的其他任务,我肯定会考虑交换一个“真正的”语言,比如Python来执行这样的任务。

< P>你可以使用<代码> Prtff和<代码> GRP:

if printf '%s\n' "${array[@]}" | grep -qFx -- "$string"; then
  : match found
fi
  • -F
    将内容匹配为字符串,而不是模式
  • -x
    匹配整行,以防止部分匹配产生误报
  • -q
    抑制输出
  • --
    防止由
    $string
if printf '%s\n' "${array[@]}" | grep -qFx -- "$string"; then
  : match found
fi