我有一个包含各种子字符串的数组
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
一种更可重用的方式:
#!/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
真的很好,这有可能得到我们未找到的物品吗?