1. 程式人生 > >【轉】Shell判斷字串包含關係的幾種方法

【轉】Shell判斷字串包含關係的幾種方法

下面是直接copy的內容: (本來是不打算copy的,但是每次用到或看的時候都要跳轉,感覺挺麻煩的。就直接copy了。)

方法一:利用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 esa

這個就比較複雜了,case in 我還沒有接觸到,不過既然有比較簡單的方法何必如此

方法五:利用替換

複製程式碼

 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