SoFunction
Updated on 2025-03-09

6 ways to determine whether a variable contains a certain string

Method 1: Use grep to find

strA="long string"
strB="string"
result=$(echo $strA | grep "${strB}")
if [[ "$result" != "" ]]
then
    echo "Include"
else
    echo "不Include"
fi

First print the long string, then grep in the long string to find the string to be searched, and record the result with the variable result. If the result is not empty, it means that strA contains strB. If the result is empty, it means it is not included.
This method makes full use of grep's characteristics and is the simplest.

Method 2: Use string operators

strA="helloworld"
strB="low"
if [[ $strA =~ $strB ]]
then
    echo "Include"
else
    echo "Not included"
fi

Use the string operator =~ to directly determine whether strA contains strB. (Isn't this more concise than the first method?)

Method 3: Use wildcards

A="helloworld"
B="low"
if [[ $A == *$B* ]]
then
    echo "Include"
else
    echo "Not included"
fi

This is also easy. Use wildcard symbol * to proxy the non-strB part of strA. If the results are equal, it means that it contains it, otherwise it does not contain it.

Method 4: Use case in statement

thisString="1 2 3 4 5"    # Source stringsearchString="1 2"        # Search stringcase $thisString in 
    *"$searchString"*) echo  "Include";;
    *) echo  "Not included" ;;
esac

This is quite complicated, I haven't come into contact with case in yet, but since there is a relatively simple method, why bother to do so.

Method 5: Use replacement

STRING_A="helloworld"
STRING_B="low"
if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]]
    then
        echo  "Not included"
    else
       echo  "Include"
    fi

This is quite complicated, too.

Method 6: Use expr, if included, it will return to the position

STRING1="hello world"
STRING2="wor"
if [[ `expr index "$STRING1" $STRING2` == 0 ]]
then
    echo "name dont contain $STRING2"
else 
    echo `expr index "$STRING1" $STRING2`
fi

If you look at *, there are actually more forms, but they basically fall into the above categories.

This is the end of this article about 6 methods for determining whether shell variables contain a certain string. For more relevant shell strings, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!