如何在 sed 中匹配多个地址? [英] How do I match multiple addresses in sed?
问题描述
我想对与多个命令的 and
或 or
匹配的任何行执行一些 sed
命令:例如,sed '50,70/abc/d'
将删除 50,70
范围内与 /abc/
匹配的所有行,或执行 的方法>sed -e '10,20s/complicated/regex/' -e '30,40s/complicated/regex/
无需重新输入 s/compicated/regex/
I want to execute some sed
command for any line that matches either the and
or or
of multiple commands: e.g., sed '50,70/abc/d'
would delete all lines in range 50,70
that match /abc/
, or a way to do sed -e '10,20s/complicated/regex/' -e '30,40s/complicated/regex/
without having to retype s/compicated/regex/
推荐答案
Logical-and
和
部分可以用大括号完成:
Logical-and
The and
part can be done with braces:
sed '50,70{/abc/d;}'
此外,可以为多个和
条件嵌套大括号.
Further, braces can be nested for multiple and
conditions.
(以上是在 GNU sed
下测试的.BSD sed
可能在小但令人沮丧的细节上有所不同.)
(The above was tested under GNU sed
. BSD sed
may differ in small but frustrating details.)
or
部分可以用分支处理:
The or
part can be handled with branching:
sed -e '10,20{b cr;}' -e '30,40{b cr;}' -e b -e :cr -e 's/complicated/regex/' file
10,20{b cr;}
对于从 10 到 20 的所有行,我们分支到标签
cr
For all lines from 10 through 20, we branch to label
cr
30,40{b cr;}
对于从 30 到 40 的所有行,我们分支到标签
cr
For all lines from 30 through 40, we branch to label
cr
b
对于所有其他行,我们跳过其余的命令.
For all other lines, we skip the rest of the commands.
:cr
这标志着标签
cr
s/complicated/regex/
这对分支到
cr
的行执行替换.This performs the substitution on lines which branched to
cr
.使用 GNU
sed
,上述语法可以稍微缩短为:With GNU
sed
, the syntax for the above can be shortened a bit to:sed '10,20{b cr}; 30,40{b cr}; b; :cr; s/complicated/regex/' file
这篇关于如何在 sed 中匹配多个地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!