shell判断字符串包含关系的几种方法

方法一:利用grep查找

1 strA="long string"
2 strB="string"
3 result=$(echo $strA | grep "${strB}")
4 if [[ "$result" != "" ]]
5 then
6     echo "包含"
7 else
8     echo "不包含"
9 fi

先打印长字符串,然后在长字符串中 grep 查找要搜索的字符串,用变量result记录结果

如果结果不为空,说明strA包含strB。如果结果为空,说明不包含。

这个方法充分利用了grep 的特性,最为简洁。

方法二:利用字符串运算符

1 strA="helloworld"
2 strB="low"
3 if [[ $strA =~ $strB ]]
4 then
5     echo "包含"
6 else
7     echo "不包含"
8 fi

利用字符串运算符 =~ 直接判断strA是否包含strB。(这不是比第一个方法还要简洁吗摔!)

方法三:利用通配符

1 A="helloworld"
2 B="low"
3 if [[ $A == *$B* ]]
4 then
5     echo "包含"
6 else
7     echo "不包含"
8 fi

这个也很easy,用通配符*号代理strA中非strB的部分,如果结果相等说明包含,反之不包含。

方法四:利用case in 语句

1 thisString="1 2 3 4 5" # 源字符串
2 searchString="1 2" # 搜索字符串
3 case $thisString in 
4      *"$searchString"*) echo Enemy Spot ;;
5      *) echo nope ;;
6 esac

方法五:利用替换

 1 STRING_A=$1
 2 STRING_B=$2
 3 if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]]
 4 then
 5     ## is not substring.
 6     echo N
 7     return 0
 8 else
 9     ## is substring.
10     echo Y
11     return 1
12 fi
原文地址:https://www.cnblogs.com/FengZeng666/p/11784386.html