温馨提示:本文翻译自stackoverflow.com,查看原文请点击:bash - Check if a string contains element of array with a shell script

bash - 检查字符串是否包含带有shell脚本的array元素

发布于 2020-04-10 23:21:43

我有一个包含各种子字符串的数组

array=(Jack Jessy Harold Ronald Boston Naomi)

我有一个包含段落的字符串

text=" Jack is maried with Jessy, they have 3 children Ronald Boston and Naomi and Harold is the last one "

我想使用bash检查文本是否包含数组中的所有字符串,但是目前可以通过其他方式获取它们,例如

if [[ $text == *${array[0]}* && $text == *${array[1]}* && $text == *${array[2]}* && $text == *${array[3]}* && $text == *${array[4]}* && $text == *${array[5]}*  ]]; then
  echo "It's there!"
fi

查看更多

提问者
StillLearningHowtodoit
被浏览
58
Philippe 2020-02-01 02:24

一种更可重用的方式:

#!/usr/bin/env bash

array=(Jack Jessy Harold Ronald Boston Naomi)

text=" Jack is maried with Jessy, they have 3 children Ronald Boston and Naomi and Harold is the last one "

check(){
    local str string=" $1 "; shift
    MAPFILE=()
    for str; do
        pattern="\b$str\b" # Word search, excluding [Jacky], for example
        [[ $string =~ $pattern ]] || MAPFILE+=($str)
    done
    test ${#MAPFILE[@]} = 0
}

if  check "$text" "${array[@]}"; then
    echo "All in"
else
    echo "Not all in : [${MAPFILE[@]}]"
fi