如果语句不起作用,则在Bash中使用正则表达式匹配

dig*_*123 6 regex linux bash shell

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

getos="red hat"
rh_reg="[rR]ed[:space:].*[Hh]at"
if [ "$getos" =~ "$rh_reg" ]; then
  getos="redhat"
fi
echo $getos
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Ini*_*ian 7

这里有很多东西需要解决

  • bash支持其[[扩展测试运算符内的正则表达式模式匹配,而不支持其POSIX标准[测试运算符
  • 从不引用我们的正则表达式匹配字符串.bash3.2引入了一个兼容性选项compat31(在Bash 1.l中的New Features下),它将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"
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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