圆括号之间的bash中的SED替换
我想使用sed检查某个字符串是否与模式匹配,然后将该匹配保存到变量中:圆括号之间的bash中的SED替换,bash,replace,sed,match,brackets,Bash,Replace,Sed,Match,Brackets,我想使用sed检查某个字符串是否与模式匹配,然后将该匹配保存到变量中: function tst2(){ string='cms(1.2;1.5;1.3)' regex='cms\(.*\)' echo -e $string if [[ $string =~ $regex ]] then myVar=$(echo -e $string | sed "s/cms\(.*\)/\1/g") echo $myVar el
function tst2(){
string='cms(1.2;1.5;1.3)'
regex='cms\(.*\)'
echo -e $string
if [[ $string =~ $regex ]]
then
myVar=$(echo -e $string | sed "s/cms\(.*\)/\1/g")
echo $myVar
else
echo "too badd!!!"
fi
}
控制台输出:
[user@home~]$ tst2
cms(1.2;1.5;1.3)
(1.2;1.5;1.3)
我希望myVar变成“1.2;1.5;1.3”(不带圆括号)myVar=$(expr$string:$regex)
这将实现您想要的功能(使用shell的内置expr
)。不过,您需要调整您的正则表达式,以:
regex='cms(\(.*)”
与括号匹配但未将其包含在结果中。myVar=$(expr$string:$regex)
这将实现您想要的功能(使用shell的内置expr
)。不过,您需要调整您的正则表达式,以:
regex='cms(\(.*)”
与括号匹配但不包含在结果中。这是一种更快的方法,无需使用sed。当使用=~运算符时,它使用填充的bash内置bash_REMATCH变量:
function tst2(){
string='cms(1.2;1.5;1.3)'
regex='cms\((.*)\)'
echo -e $string
if [[ $string =~ $regex ]]
then
echo ${BASH_REMATCH[1]}
else
echo "too badd!!!"
fi
}
这是一种不必使用sed的更快的方法。当使用=~运算符时,它使用填充的bash内置bash_REMATCH变量:
function tst2(){
string='cms(1.2;1.5;1.3)'
regex='cms\((.*)\)'
echo -e $string
if [[ $string =~ $regex ]]
then
echo ${BASH_REMATCH[1]}
else
echo "too badd!!!"
fi
}
myvar=$(sed's/cms(\(.*))/\1/g'引用变量并用单引号而不是双引号分隔脚本。myvar=$(sed's/cms(\(.*))/\1/g'引用变量并用单引号而不是双引号分隔脚本。