【shell】判断字符串包含的方法

!!一定要看最底部的说明

 方法一?

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

方法二? 

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

方法三? 

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

方法四? 

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

方法五? 

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

 

 

说明!

没有深入学过shell脚本,实际开发中想要顺畅的操作整个流程,就用到了条件判断,但是我不会去百度搜了很多就以上几种方式

看到方法后边的?了吧!

好几个方法有坑!

方法二     [[ =~ ]]

方法三     [[ ==** ]]

这两个实测只会走then  就是成立的代码块里,下面放图,大家可以自己测试一下!

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

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

可用 方法

方法一、grep

有一些需要注意的地方

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

!=左右两边   要有空格

[[右边要有空格
]]左边要有空格

方法四、case   in 

in后边每个选项以  通配符*  开始,以  后括号)   结尾

每个选项下的代码块以  双分号;;  结尾

最后一个选后边跟esac结束

猜你喜欢

转载自blog.csdn.net/qq_44065303/article/details/112539728