使用 sed 复制行并在行本身之前进行替换

问题描述 投票:0回答:1

这是我的意见

T

dummy
This is a line
dummy
dummy
this is another line

输出应该是

dummy
# This is a line
dummy
dummy
This is a line
# this is another line
this is another line

这在我看来非常简单...

刚刚尝试了下面的 sed,但这不会添加找到的模式。它只是在行上方打印#。

 sed -i '/^this/I i\ '#' & ' $file  

想法?谢谢。

似乎这种语法不是实现此目的的正确方法。

linux sed
1个回答
0
投票

使用

sed

$ sed '/^this/I{h;s/^/# /;G}' input_file
# This is a line
This is a line
# this is another line
this is another line

或者吞掉整个输入

$ sed -z 's/this[^\n]*\n/# &&/Ig' input_file
# This is a line
This is a line
# this is another line
this is another line

如果

awk
是一个选项

$ awk '/[Tt]his/{print "# "$0}1' input_file
# This is a line
This is a line
# this is another line
this is another line
© www.soinside.com 2019 - 2024. All rights reserved.