Check if variable match with a list of sub-strings

Viewed 72

I am trying to write a script that filters for certain words.

This is the method I was using. it was working well but when the number of possible matches became too large it doesn't do the job anymore. I am not sure if this method has some sort of limitations. So any alternatives are welcome.

str="He is driving a car"
if [ "$str" != "${str/car/}" ] || [ "$str" != "${str/bus/}" ] || [ "$str" != "${str/truck/}" ] || [ "$str" != "${str/vehicle/}" ];then
echo "Substring found"
else
echo "Substring not found"
fi
3 Answers

I don't think that there's anything wrong with your method, although I would say that it is quite long to write.

Since you're using bash, you can use an extended glob, which reduces the length of your code significantly:

# enable extended globs
shopt -s extglob

# match anything containing car, bus, truck or vehicle
if [[ $str = *@(car|bus|truck|vehicle)* ]]; then
  echo "Substring found"
fi

# unset extended glob mode
shopt -u extglob

Or you can simply use the following regular expression matching operator =~ that compares the string on the left to the extended regular expression on the right

str="He is driving a car"
vehicules="car|bus|truck|vehicle"

if [[ $str =~ $vehicules ]]; then
  echo "Substring found"
fi

A solution using expr match can also be used.

This worked well for me

case ${str} in car* | bus* | truck* | vehicle*)
    echo "Substring found"
esac
Related