当一行与模式匹配时,我可以在sed中执行两个命令吗?

问题描述 投票:2回答:2

我有一个工作sed命令搜索rm a-file,评论它并在它下面添加另一行(rm another-file):

sed -e '/^rm a-file/s;^;# ;'            \
    -e '/# rm a-file/a rm another file' \
    my.script

我想知道是否有可能将编辑,注释和附加组合成一个命令,以便我必须只指定匹配模式(/^rm a-file/)一次。

如果重要,我正在使用gnu sed。

sed
2个回答
3
投票

您可以像这样重新组合它:

ON命令:

$ cat commands.sed 
/^rm a-file/{
  s@^@# @
  a rm another file
}

INPUT:

$ cat myscript.sh 
rm a-file
blabla
rm a-file
blabla2

OUTPUT:

$ sed -f commands.sed myscript.sh                              
# rm a-file
rm another file
blabla
# rm a-file
rm another file
blabla2

说明:

这将查找以rm a-file开头然后用^替换#的行(注释初始rm命令)然后只有当行遵守条件rm another file时才会追加行^rm a-file

正如Sundeep所建议的那样,这也可以在单行中完成:(https://www.gnu.org/software/sed/manual/sed.html#Commands-Requiring-a-newline

sed -e '/^rm a-file/{s@^@# @; a rm another file' -e '}'

0
投票

使用GNU sed,这个特殊情况也可以用简单的替换来覆盖

$ sed 's/^rm a-file.*/# &\nrm another file/' my.script
# rm a-file
rm another file
blabla
# rm a-file
rm another file
blabla2
  • ^rm a-file.*匹配从rm a-file开始的线,然后.*捕获其余的线重复使用
  • # &\nrm another file这里的&将有完整匹配的文本,而\n将添加所需的换行
© www.soinside.com 2019 - 2024. All rights reserved.