sed正则表达式中的布尔OR

问题描述 投票:16回答:4

我正在尝试在配置文件中替换名为boots的包的所有引用。

行格式为add fast (package OR pkg) boots-(any-other-text),例如:

add fast package boots-2.3
add fast pkg boots-4.5

我想用以下代替:

add fast pkg boots-5.0

我尝试过以下sed命令:

sed -e 's/add fast (pkg\|package) boots-.*/add yinst pkg boots-5.0/g'
sed -e 's/add fast [pkg\|package] boots-.*/add yinst pkg boots-5.0/g'

什么是正确的正则表达式?我想我在布尔或(packagepkg)部分缺少一些东西。

regex sed logical-operators
4个回答
21
投票
sed -e 's/add fast \(pkg\|package\) boots-.*/add yinst pkg boots-5.0/g'

您可以通过两次执行来避免OR

sed 's/add fast pkg boots-.*/add yinst pkg boots-5.0/g
s/add fast package boots-.*/add yinst pkg boots-5.0/g'

17
投票

使用扩展的正则表达式模式,不要逃避|

sed -E -e 's/add fast (pkg|package) boots-.*/add yinst pkg boots-5.0/g'

7
投票

你混合BRE和ERE要么逃避()|,要么没有。

sed默认使用基本正则表达式,因此使用扩展正则表达式是依赖于实现的,例如,与BSD sed你使用-E开关,GNU sed记录为-r,但-E也适用。


0
投票

GNU (Linux):

1)制作以下随机字符串

   cidr="192.168.1.12"
   cidr="192.168.1.12/32"
   cidr="192.168.1.12,8.8.8.8"

空白

2)sed with -r使用GNU中的逻辑运算符,如@Thor提到的那样,并且-i用于动态编辑匹配找到的文件

$ echo '<user id="1000" cidr="192.168.1.12">' > /tmp/1000.xml
$ sed -r -i \ 
  s/'cidr="192.168.1.12\/32"|cidr="192.168.1.12"|192.168.1.12,'/''/ /tmp/1000.xml

-r = GNU sed
-i = search / match/ edit the changes to the file on the fly
© www.soinside.com 2019 - 2024. All rights reserved.