带有‘+’的 sed 正则表达式不起作用-为什么?

带有‘+’的 sed 正则表达式不起作用-为什么?

我不明白。我想将字符串替换ip-up 9490:notify_rcip-up ****:notify_rc。我认为这很简单:

echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'

但不,它对我来说不起作用,输出是ip-up 9490:notify_rc。为什么?我该怎么办?

[0-9]+我试过:等\S+ [:num:]+,尝试将-rswitch 添加到sed命令中,但没有成功。每次的结果都是原始字符串。

如果我改为+*那么它就可以工作了;但是加号有什么问题?

更新
以下是一个简短的示例:

echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/' 
ip-up 9490:notify_rc
echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/' -r
ip-up 9490:notify_rc
echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/' -E
ip-up 9490:notify_rc

sed --version
sed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Jay Fenlason, Tom Lord, Ken Pizzini,
and Paolo Bonzini.
GNU sed home page: <http://www.gnu.org/software/sed/>.
General help using GNU software: <http://www.gnu.org/gethelp/>.
E-mail bug reports to: <[email protected]>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.

答案1

不要sed在 -e 开关后面放置任何东西(脚本除外)。

$ echo "ip-up 9490:notify_rc" | sed -r -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'
ip-up ****:notify_rc

答案2

你正在触及正则表达式和延长正则表达式。

一个或多个运算符属+​​于扩展正则表达式。您可以sed使用选项-r或来判断该正则表达式是否为扩展正则表达式-E

echo "ip-up 9490:notify_rc" | sed -r -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'

如果您使用(基本)正则表达式,则需要转义该运算符,以使其不被视为字符。

echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]\+:notify_rc/ip-up ****:notify_rc/'

答案3

如果字符串中没有其他数字需要保留,则可以使用以下语法:

sed -e "s/[0-9]/\*/g"

这将用星号替换任何数字。

相关内容