[Shell] How to determine whether a string contains

! ! Be sure to read the instructions at the bottom

 method one?

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

Method Two? 

strA="helloworld"
strB="low"
if [[ $strA =~ $strB ]]
then
    echo "包含"
else
    echo "不包含"
fi

Method three? 

A="helloworld"
B="low"
if [[ $A==*$B* ]]
then
    echo "包含"
else
    echo "不包含"
fi

Method four? 

thisString="1 2 3 4 5" # 源字符串
searchString="1 2" # 搜索字符串
case $thisString in
    *"$searchString"*) echo "包含" ;;
    *) echo "不包含" ;;
esac

Method five? 

STRING_A=$1
STRING_B=$2
if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]];then
    ## is not substring.
    echo "包含"
    exit 0
else
    ## is substring.
    echo "不包含"
    exit 1
fi

 

 

Explanation!

I haven't studied shell scripts in depth. In actual development, if you want to operate the entire process smoothly, conditional judgment is used, but I will not go to Baidu to search a lot of the above methods.

See the method behind? Got it!

There are pitfalls in several methods!

Method two      [[ =~ ]]

Method Three      [[ ==** ]]

These two actual tests will only go in the code block where the then is established. Below are the pictures, you can test it yourself!

===========================================================================

===========================================================================

Available methods

Method one, grep

There are some things to pay attention to

if [[ "$result" != "" ]]

!= There must be spaces on the left and right sides   

[[There must be a space on the right
]] There must be a space on the left

Method four, case in 

Each option after in starts with a wildcard * and ends with a bracket)

The code block under each option ends with a double semicolon;;

End with esac after the last selection

 

 

Guess you like

Origin blog.csdn.net/qq_44065303/article/details/112539728