【问题标题】:Regex stored in a shell variable doesn't work between double brackets存储在 shell 变量中的正则表达式在双括号之间不起作用
【发布时间】:2018-07-27 00:07:19
【问题描述】:
下面是我正在处理的更大脚本的一小部分,但下面给我带来了很多痛苦,这导致更大脚本的一部分无法正常运行。目的是检查变量是否具有匹配red hat 或Red 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】:
这里有很多问题需要解决
就这样吧
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