gpt4 book ai didi

存储在 shell 变量中的正则表达式在双括号之间不起作用

转载 作者:IT王子 更新时间:2023-10-29 00:44:15 26 4
gpt4 key购买 nike

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

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

任何帮助将不胜感激。

最佳答案

这里有很多事情要解决

  • 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 选项,只需使用扩展测试运算符 [[ 和一个不带引号的正则表达式字符串变量。

关于存储在 shell 变量中的正则表达式在双括号之间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48820712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com