• [shell] 判断字符串是否包含子字符串方法([[ 、=~、##、%%)


    描述

    本文是希望通过 shell 语法判定字符串 str 中是否包含 subStr ,尝试使用 shell 来解决。
    其中:

    str="This is my test string search_string"     #被测试字符串
    subStr="search_"                               #待查找的字符串1
    subStr2="search_TTT"                           #待查找的字符串2
    
    • 1
    • 2
    • 3

    具体实现方法

    方法1

    if [[ ${str} == *${subStr}* ]] ;then
        echo -e "String '${str}' contain substring: '${subStr}'."
    else
        echo -e "String '${str}' don't contain substring: '${subStr}'."
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5

    其中 [[ ... ]] (注意两边有空格)是Bash在 2.02 版中, 引入的扩展测试命令,它以其他语言的程序员更熟悉的方式执行比较。
    请注意 **[[ 是关键字**,而不是命令。

    使用 [[ … ]] 测试构造,而不是 [ … ] 可以防止脚本中的许多逻辑错误。 例如,&&、||、< 和 > 运算符在 [[ ]] 测试中工作,而在 [ ] 构造中给出错误。

    具体可以参看 7.1. Test Constructs

    方法2

    if echo ${str} | grep ${subStr} ;then
        echo -e "String '${str}' contain substring: '${subStr}'."
    else
        echo -e "String '${str}' don't contain substring: '${subStr}'."
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5

    此种方式有个小的问题是,if 判定中 echo 会将 str 输出并打印到屏幕上去。可以考虑借用上面的关键字 [[ 来改进:

    if [[ $(echo ${str} | grep ${subStr}) ]];then
        echo -e "String '${str}' contain substring: '${subStr}'."
    else
        echo -e "String '${str}' don't contain substring: '${subStr}'."
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5

    方法3

    if [[ ${str} =~ ${subStr} ]] ;then
        echo -e "String '${str}' contain substring: '${subStr}'."
    else
        echo -e "String '${str}' don't contain substring: '${subStr}'."
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5

    此种应用比较少见,主要是利用 =~ 操作符。即对双括号内的正则表达式 进行匹配运算测试。(Perl 也有类似的运算符)。

    #!/bin/bash
    
    variable="This is a fine mess."
    echo "$variable"
    
    # Regex matching with =~ operator within [[ double brackets ]].
    if [[ "$variable" =~ T.........fin*es* ]]
    # NOTE: As of version 3.2 of Bash, expression to match no longer quoted.
    then
      echo "match found"
          # match found
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    或者

    #!/bin/bash
    input=$1
    
    if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
    #                 ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
    # NNN-NN-NNNN (where each N is a digit).
    then
      echo "Social Security number."
      # Process SSN.
    else
      echo "Not a Social Security number!"
      # Or, ask for corrected input.
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    具体可以参看https://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF

    方法4

    if [ -z "${str##*$subStr*}" ];then
        echo -e "String '${str}' contain substring: '${subStr}'."
    else
        echo -e "String '${str}' don't contain substring: '${subStr}'."
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5

    和下面的例子等价

    if [ -z "${str%%*$subStr*}" ];then
        echo -e "String '${str}' contain substring: '${subStr}'."
    else
        echo -e "String '${str}' don't contain substring: '${subStr}'."
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5

    参考:https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash/229585#229585
    中的示例:

    string='echo "My string"'
    for reqsubstr in 'o "M' 'alt' 'str';do
      if [ -z "${string##*$reqsubstr*}" ] ;then
          echo "String '$string' contain substring: '$reqsubstr'."
        else
          echo "String '$string' don't contain substring: '$reqsubstr'."
        fi
      done
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    其中
    #是将${var}中的左边(键盘上 #$ 的左边)的${Pattern}去掉;
    %是将${var}中的右边(键盘上 %$ 的右边)的${Pattern}去掉;
    其中单一符号#%是最小匹配;两个符号##%%则是最大匹配。
    更多示例请参看:shell 的 ${ }中 ##、%%、// 使用方法及举例

    Reference

    HTML 版本:Advanced Bash-Scripting Guide
    PDF 版本:Advanced Bash-Scripting Guide

  • 相关阅读:
    android8.1中用libtinyalsa编写sound-hal驱动
    SimVODIS++: Neural Semantic Visual Odometry in Dynamic Environments 论文阅读
    为什么不建议你用 MongoDB 这类产品替代时序数据库?
    .Net6 Api Swagger配置
    有哪些方法下载外文文献?
    MongoDB中的嵌套List操作
    通过 python 生成随机数据,并批量插入到 Amazon DocumentDB (或mongodb) 中
    【复杂网络】关于复杂网络中的动力学系统重构的文献资料整理
    初识数据结构
    来自云仓酒庄品牌雷盛红酒分享为什么高海拔的酒价格更高?
  • 原文地址:https://blog.csdn.net/lm_hao/article/details/126856298