问题描述
下面是我正在处理的较大脚本的一小部分,但是下面给我带来了很多痛苦,这导致较大脚本的一部分无法正常运行.目的是检查变量是否具有匹配red hat
或Red Hat
的字符串值.如果是,则将变量名称更改为redhat
.但这与我使用的正则表达式不太匹配.
The below is a small part of a bigger script I'm working on, but the below is giving me a lot of pain which causes a part of the bigger script to not function properly. The intention is to check if the variable has a string value matching red hat
or Red Hat
. If it is, then change the variable name to redhat
. But it doesn't quite match the regex I've used.
getos="red hat"
rh_reg="[rR]ed[:space:].*[Hh]at"
if [ "$getos" =~ "$rh_reg" ]; then
getos="redhat"
fi
echo $getos
任何帮助将不胜感激.
推荐答案
这里有多个问题需要解决
There are a multiple things to fix here
-
bash
在其[[
扩展测试操作符中而不是在POSIX标准[
测试操作符 中支持正则表达式模式匹配. - 切勿引用我们的正则表达式匹配字符串.
bash
3.2引入了兼容性选项compat31
(在Bash 1.l中的新功能下) ),它将bash正则表达式的引用行为恢复为3.1,支持正则表达式字符串的引用. - 修复正则表达式以使用
[[:space:]]
而不只是[:space:]
bash
supports regex pattern matching within its[[
extended test operator and not within its POSIX standard[
test operator- Never quote our regex match string.
bash
3.2 introduced a compatibility optioncompat31
(under New Features in Bash 1.l) which reverts bash regular expression quoting behavior back to 3.1 which supported quoting of the regex string. - Fix the regex to use
[[:space:]]
instead of just[:space:]
所以就做
getos="red hat"
rh_reg="[rR]ed[[:space:]]*[Hh]at"
if [[ "$getos" =~ $rh_reg ]]; then
getos="redhat"
fi;
echo "$getos"
或启用扩展外壳程序选项中的compat31
选项
or enable the compat31
option from the extended shell option
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选项.
But instead of messing with those shell options just use the extended test operator [[
with an unquoted regex string variable.
这篇关于如果语句不起作用,则在Bash中进行正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!