繁体   English   中英

在sed中的相同匹配项上执行多个命令

[英]execute multiple commands on the same match in sed

我知道我可以针对sed中的匹配运行命令,如下所示:

$ cat file
line1
line2
line3
line4

$ sed -e "/^line2/ s/^/# /" file
line1
# line2
line3
line4

是否可以在同一匹配项上运行多个命令,例如s/^/#/s/$/ # invalid/

我尝试将两者都添加,但出现错误:

$ sed -e "/^line2/ s/^/# / s/$/ # /" file
sed: -e expression #1, char 18: unknown option to `s'

我尝试使用; 但这似乎放弃了初始匹配并在输入的每一行上执行:

$ sed -e "/^line2/ s/^/# / ; s/$/ # /" file
line1 #
# line2 #
line3 #
line4 #

EDIT2:如果您非常希望在满足条件时执行多条语句,则可以按以下方式使用{..}块语句。(刚刚看到@Tiw在注释中也建议了相同的内容。)

sed '/^line2/ {s/^/#/; s/$/ # invalid/}'  Input_file


编辑:在此处添加1 sed更多解决方案。 (我简单地把其起始线line2在存储缓冲器\\1然后简单而把取代的/ NEW_VALUE添加#之前和附加# invalid后)

sed '/^line2/s/\(.*\)/# \1 # invalid/'  Input_file


您可以尝试以下吗?

sed "/^line2/ s/^/# /;/^line2/s/$/ # invalid/"  Input_file

什么是你尝试发生的事情,只是进行简单地替代其每行发生的事情,不论它要么从开始line2或没有,所以当你替换之前,给这个条件应该工作,然后。

您可以尝试使用扩展的正则表达式:

sed -r -e '/^line2/ s/(.*)/# \1 #/' file

您不需要多个命令,只需替换以line2开头的行:

sed "s/^line2.*/# & #/" file

这可能对您有用(GNU sed):

sed '/^line2/!b;s/^/.../;s/$/.../' file

在这里,正则表达式使用!取反! 命令和b命令本身分支到所有sed命令的末尾。 也许更简单的例子是:

sed ' /^lines/bjumphere;bjumpthere;:jumphere;s/^/.../;s/$/.../;:jumpthere' file

当然上面也可以写成:

sed '/^line2/{s/^/.../;s/$/.../}' file

当编写一个以换行符结尾的衬线(例如iacrRwW命令)并且需要其他命令时,可以为sed脚本的每个部分调用-e选项,例如:

sed -e '/^line2/{i\a couple of lines\ninserted before "line2"' -e '}' file

也可以这样写:

sed '/^line2/i\a couple of lines\ninserted before "line2"' file

如果有要被执行没有后续sed命令,但是如果line2需要被太删除:

sed -e '/^line2/b;!i\a couple of lines\ninserted before "line2 then line2 deleted"' -e 'd' file

但是,更好的方法是使用c命令。

sed '/^line2/c\a line changed and a line\nappended for "line2"' file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM