问题描述
我想对与和或匹配的任何行执行一些 sed 命令>或的多个命令:例如 sed '50,70 / abc / d'将删除匹配 / abc / 的,或者 sed -e '10,20s / regex /'-e '30,40s / complex / regex / ,而无需重新输入 s / compicated / regex /
逻辑和
和部分可以使用大括号:
sed '50,70 {/ abc / d;}'
此外,大括号可以嵌套多个和条件。 / p>
(以上是在GNU sed 下测试的BSD sed
逻辑或
或部分可以用分支处理:
sed -e '10,20 {b cr; }'-e '30,40 {b cr;}'-eb -e:cr -e's / complex / regex /'file
-
10,20 {b cr;}
对于从10到20的所有行,我们分支到 cr
-
30,40 {b cr;}
对于从30到40的所有行, c $ c> cr
-
b
对于所有其他行,我们跳过其余的命令。
-
:cr
这标记了标签 cr
-
s / complex / regex /
code> cr 。
,上面的语法可以缩短为:
sed '10, b cr}; 30,40 {b cr}; b; :cr; s / complex / 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
The and part can be done with braces:
sed '50,70{/abc/d;}'
Further, braces can be nested for multiple and conditions.
(The above was tested under GNU sed. BSD sed may differ in small but frustrating details.)
Logical-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;}
For all lines from 10 through 20, we branch to label cr
30,40{b 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
This marks the label cr
s/complicated/regex/
This performs the substitution on lines which branched to cr.
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中匹配多个地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!