Warm tip: This article is reproduced from stackoverflow.com, please click
awk bash sed shell

Check if a string contains element of array with a shell script

发布于 2020-04-07 10:11:34

I have an array containing various substring

array=(Jack Jessy Harold Ronald Boston Naomi)

and i have a string containing a paragraph

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

I want to check using bash if the text contain all the strings that are inside the array but in a different way at the moment I can get them like that

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
Questioner
StillLearningHowtodoit
Viewed
73
Philippe 2020-02-01 02:24

A more reusable way:

#!/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