目录

工欲善其事

实践出真知

活跃标签: linux java mysql 待分类 js springboot win10 电路 vue macOS nginx esp32 windows git docker idea maven esp8266 python Arduino

存档:

X

Linux Shell 中的字符串判断

判断两字符串是否包含

  1. 利用grep查找

    strA="long string"
    strB="string"
    result=$(echo $strA | grep "${strB}")
    if [[ "$result" != "" ]]
    then
        echo "包含"
    else
        echo "不包含"
    fi
    
  2. 利用字符串运算符

    strA="helloworld"
    strB="low"
    if [[ $strA =~ $strB ]]
    then
        echo "包含"
    else
        echo "不包含"
    fi
    
  3. 利用通配符

    A="helloworld"
    B="low"
    if [[ $A == *$B* ]]
    then
        echo "包含"
    else
        echo "不包含"
    fi
    
  4. 利用case in 语句

    thisString="1 2 3 4 5" # 源字符串
    searchString="1 2" # 搜索字符串
    case $thisString in 
        *"$searchString"*) echo Enemy Spot ;;
        *) echo nope ;;
    esa
    
  5. 利用替换

    STRING_A=$1
    STRING_B=$2
    if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]]
        then
            ## is not substring.
            echo N
            return 0
        else
            ## is substring.
            echo Y
            return 1
        fi
    

标题:Linux Shell 中的字符串判断
作者:llilei
地址:http://solo.llilei.work/articles/2022/06/11/1654931178109.html