Shell脚本中判断字符串包含的集中方式

1.字段 grep

案例: 
str1="abcdefgh"
str2="def"
result=$(echo $str1 | grep "${str2}")
if [[ "$result" != "" ]]
then
    echo "包含"
else
    echo "不包含"
fi
//输出结果: 包含

2. 字符串运算符 =~:

案例:
str1="abcdefgh"
str2="def"
if [[ $str1 =~ $str2 ]]
then
    echo "包含"
else
    echo "不包含"
fi
//输出结果: 包含

3. 正则表达式中的通配符 *:

案例: 
str1="abcdefgh"
str2="def"
if [[ $str1 == *$str2* ]]
then
    echo "包含"
else
    echo "不包含"
fi
//输出结果: 包含

4. 语句case in

案例:
str1="abcdefgh"
str2="def"
case $str1 in 
    *"$str2"*) echo "包含" ;;
    *) echo "不包含" ;;
esac
//输出结果: 包含

5.利用替换:

案例:
str1="abcdefgh"
str2="def"
if [[ ${str1/${str2}//} == $str1 ]]
    then
       echo "不包含"
    else
      echo "包含"
fi
//输出结果:包含

猜你喜欢

转载自blog.csdn.net/m0_37779570/article/details/82181986
今日推荐