一、Shell字符串包含另一個字符串
Shell字符串包含另一個字符串的方式有很多種,下面列舉了其中常用的三種方法:
# 方法一:使用“=”判斷 str="hello world" if [ "$str" = "*hello*" ]; then echo "包含hello" fi # 方法二:使用“==”判斷 str="hello world" if [ "$str" == "*hello*" ]; then echo "包含hello" fi # 方法三:使用“[[...]]”判斷 str="hello world" if [[ $str == *hello* ]]; then echo "包含hello" fi
二、Shell字符串包含某字符
Shell字符串包含某字符的方式也很多,下面列舉了其中常用的兩種方法:
# 方法一:使用“[]”判斷 str="hello world" if [[ "$str" == *"h"* ]]; then echo "包含h" fi # 方法二:使用“grep”命令 str="hello world" if echo "$str" | grep -q "h"; then echo "包含h" fi
三、Shell字符串拼接
Shell字符串拼接有多種方法,下面列舉了其中常用的三種方法:
# 方法一:使用“+”拼接 str1="hello" str2="world" str3=$str1+$str2 echo $str3 # 方法二:使用“.”拼接 str1="hello" str2="world" str3=$str1.$str2 echo $str3 # 方法三:使用括號拼接 str1="hello" str2="world" str3=$str1$str2 echo $str3
四、Shell字符串包含子串
Shell字符串包含子串的方法有多種,下面列舉了其中常用的兩種方法:
# 方法一:使用“[]”判斷 str="hello world" if [[ "$str" == *"he"* ]] && [[ "$str" == *"lo"* ]]; then echo "包含子串hel和lo" fi # 方法二:使用“grep”命令 str="hello world" if echo "$str" | grep -q "he" && echo "$str" | grep -q "lo"; then echo "包含子串hel和lo" fi
五、Shell字符串比較
Shell字符串比較的方法有很多種,下面列舉了其中常用的三種方法:
# 方法一:使用“==”判斷 str1="hello" str2="world" if [ "$str1" == "$str2" ]; then echo "相等" else echo "不相等" fi # 方法二:使用“!=”判斷 str1="hello" str2="world" if [ "$str1" != "$str2" ]; then echo "不相等" else echo "相等" fi # 方法三:使用“-z”判斷是否為空 str="" if [ -z "$str" ]; then echo "為空" else echo "非空" fi
六、Shell字符串包含判斷
Shell字符串包含判斷常常用到“[]”和“grep”命令,下面列舉了其中的兩種方法:
# 方法一:使用“[]”判斷 str="hello world" if [[ "$str" == *"hello"* ]]; then echo "包含hello" else echo "不包含hello" fi # 方法二:使用“grep”命令 str="hello world" if echo "$str" | grep -q "hello"; then echo "包含hello" else echo "不包含hello" fi
七、Shell字符串包含特殊符號
對於包含特殊符號的字符串,需要使用轉義符“\”對其進行轉義,下面是一個例子:
str="hello \"world\"" if [[ "$str" == *"\"world\"" ]]; then echo "包含\"world\"" fi
八、Shell中的字符串包含
在Shell腳本中,字符串包含常常用於條件語句中的判斷,下面是一個例子:
str="hello world" if [[ "$str" == *"hello"* ]]; then echo "包含hello" fi
九、Shell判斷字符串包含字符
Shell判斷字符串包含字符是比較簡單的,只需要使用“[]”和“grep”命令即可,下面是一個例子:
str="hello world" if [[ "$str" == *"h"* ]]; then echo "包含h" fi if echo "$str" | grep -q "h"; then echo "包含h" fi
以上就是關於Shell字符串包含的詳細介紹,希望能對大家的Shell腳本編程有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/291635.html