【问题标题】:Bash regular expression not matching inside if [duplicate]如果 [重复],Bash 正则表达式内部不匹配
【发布时间】:2017-03-12 12:52:48
【问题描述】:

我有一个文件/tmp/gish.dat,其中包含一个数字(大于 0,以及一个或多个数字)或什么都不包含。

如果存在数字,我希望我的函数回显# 以及数字(例如#64)。如果没有数字,我希望我的函数什么都不做。

   get_issue() {
        if [ -f "/tmp/gish.dat" ]
        then
            iss=$(cat /tmp/gish.dat | grep -Eo '[0-9]+')
            if [[ iss =~ '[0-9]+' ]]
            then
              echo "#$iss"
            fi
        fi
    }

由于某种原因,内部 if 永远不会匹配。对 bash 非常陌生。

【问题讨论】:

  • 认为您的变量缺少美元符号。在 if 条件下将其更改为 $iss -。
  • 假设您的外部如果工作正常,请尝试打印 shell 调用 (iss) 的结果并检查它是否正常工作。编辑:很确定你错过了美元符号,正如本杰明已经提到的那样。
  • 也许我还建议您查看 -s 选项来测试文件是否为空:)
  • Protip:shellcheck 自动检测此类问题

标签: bash shell


【解决方案1】:

如果你在[[...]] 中引用一个正则表达式,它只是一个字符串。

'[0-9]+' 替换为[0-9]+

【讨论】:

    【解决方案2】:

    你可以这样重写你的代码:

       get_issue() {
            if [ -f "/tmp/gish.dat" ]
            then
                iss=$(grep -Eo '[0-9]+' /tmp/gish.dat)
                if [[ $iss ]]
                then
                  echo "#$iss"
                fi
            fi
        }
    

    由于grep -Eo 仅提取匹配的数字部分,因此无需再次将提取的字符串与if 中的正则表达式进行匹配。只要$iss 不为空,[[ $iss ]] 就为真。

    【讨论】:

    • 谢谢,太好了。
    【解决方案3】:

    如果您需要打印 #64、#45 等内容,请按如下方式更改您的代码,

     if [ -f "/tmp/gish.dat" ]
        then
            iss=$(cat /tmp/gish.dat | grep -Eo '[0-9]+' | tr '\n' ' ')
            for isss in $iss    
            do  
                    if [[ $isss =~ '[0-9]+' ]]
                    then
                      echo "#$isss"
                    fi  
            done;
    

    fi

    看看这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2012-10-31
      相关资源
      最近更新 更多