【问题标题】:Regex stored in a shell variable doesn't work between double brackets存储在 shell 变量中的正则表达式在双括号之间不起作用
【发布时间】:2018-07-27 00:07:19
【问题描述】:

下面是我正在处理的更大脚本的一小部分,但下面给我带来了很多痛苦,这导致更大脚本的一部分无法正常运行。目的是检查变量是否具有匹配red hatRed Hat 的字符串值。如果是,则将变量名称更改为redhat。但它与我使用的正则表达式不太匹配。

getos="red hat"
rh_reg="[rR]ed[:space:].*[Hh]at"
if [ "$getos" =~ "$rh_reg" ]; then
  getos="redhat"
fi
echo $getos

任何帮助将不胜感激。

【问题讨论】:

    标签: regex linux bash shell


    【解决方案1】:

    这里有很多问题需要解决

    • bash 在其 [[ 扩展测试运算符中支持正则表达式模式匹配,但在其 POSIX 标准 [ 测试运算符中不支持
    • 永远不要引用我们的正则表达式匹配字符串。 bash 3.2 introduced a compatibility option compat31 (under New Features in Bash 1.l) 将 bash 正则表达式引用行为恢复为支持正则表达式字符串引用的 3.1。
    • 修复正则表达式以使用[[:space:]] 而不仅仅是[:space:]

    就这样吧

    getos="red hat"
    rh_reg="[rR]ed[[:space:]]*[Hh]at"
    if [[ "$getos" =~ $rh_reg ]]; then 
        getos="redhat"
    fi;
    
    echo "$getos"
    

    或从扩展 shell 选项中启用 compat31 选项

    shopt -s compat31
    getos="red hat"
    rh_reg="[rR]ed[[:space:]]*[Hh]at"
    if [[ "$getos" =~ "$rh_reg" ]]; then 
        getos="redhat"
    fi
    echo "$getos"
    shopt -u compat31
    

    但不要弄乱这些 shell 选项,只需使用扩展测试运算符 [[ 和一个不带引号的正则表达式字符串变量。

    【讨论】:

      【解决方案2】:

      有两个问题:

      首先,替换:

      rh_reg="[rR]ed[:space:].*[Hh]at"
      

      与:

      rh_reg="[rR]ed[[:space:]]*[Hh]at"
      

      [:space:] 这样的字符类只有在方括号中时才有效。此外,您似乎想匹配零个或多个空格,即[[:space:]]* 而不是[[:space:]].*。后者将匹配一个空格,后跟零个或多个任何内容。

      二、替换:

      [ "$getos" =~ "$rh_reg" ]
      

      与:

      [[ "$getos" =~ $rh_reg ]]
      

      正则表达式匹配需要 bash 的扩展测试:[[...]]。 POSIX 标准测试[...] 没有该功能。此外,在 bash 中,正则表达式仅在不加引号时才有效。

      示例:

      $ rh_reg='[rR]ed[[:space:]]*[Hh]at'
      $ getos="red Hat"; [[ "$getos" =~ $rh_reg ]] && getos="redhat"; echo $getos
      redhat
      $ getos="RedHat"; [[ "$getos" =~ $rh_reg ]] && getos="redhat"; echo $getos
      redhat
      

      【讨论】:

        猜你喜欢
        • 2020-06-29
        • 1970-01-01
        • 2013-01-18
        • 2013-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        相关资源
        最近更新 更多