';sed';:如何在字符串匹配后添加新行+;2行

';sed';:如何在字符串匹配后添加新行+;2行,sed,Sed,我想在字符串匹配+2行之后添加新行 这是我的档案: allow-hotplug eth0 auto eth0 iface eth0 inet static address 172.16.2.245 netmask 255.255.254.0 gateway 192.168.1.1 allow-hotplug eth1 #auto eth1 iface eth1 inet static address 192.168.0.240 netmask 255.255.255.0 iface eth2

我想在字符串匹配+2行之后添加新行

这是我的档案:

allow-hotplug eth0
auto eth0
iface eth0 inet static
address 172.16.2.245
netmask 255.255.254.0
gateway 192.168.1.1

allow-hotplug eth1
#auto eth1
iface eth1 inet static
address 192.168.0.240
netmask 255.255.255.0

iface eth2 inet static
address 192.168.2.240
netmask 255.255.255.0
我想在找到'iface eth1'+2行之后添加'gateway 192.168.1.1'

示例:执行sed命令后需要得到什么

allow-hotplug eth0
auto eth0
iface eth0 inet static
address 172.16.2.245
netmask 255.255.254.0
gateway 172.16.2.254

allow-hotplug eth1
#auto eth1
iface eth1 inet static
address 192.168.0.240
netmask 255.255.255.0
gateway 192.168.1.1

iface eth2 inet static
address 192.168.2.240
netmask 255.255.255.0
我知道如何在后面查找和移动2行,在特定字符串后面追加行,等等,但不合并这2个操作。
Steph

如果要在该块末尾添加行,请尝试以下操作:

awk -v RS="" -v ORS="\n\n" '/iface eth1/{$0=$0"\ngateway 192.168.1.1"}1' file 
与您的文件一起:

kent$  cat file
allow-hotplug eth0
auto eth0
iface eth0 inet static
address 172.16.2.245
netmask 255.255.254.0
gateway 192.168.1.1

allow-hotplug eth1
#auto eth1
iface eth1 inet static
address 192.168.0.240
netmask 255.255.255.0

iface eth2 inet static
address 192.168.2.240
netmask 255.255.255.0

kent$  awk -v RS="" -v ORS="\n\n" '/iface eth1/{$0=$0"\ngateway 192.168.1.1"}1' file
allow-hotplug eth0
auto eth0
iface eth0 inet static
address 172.16.2.245
netmask 255.255.254.0
gateway 192.168.1.1

allow-hotplug eth1
#auto eth1
iface eth1 inet static
address 192.168.0.240
netmask 255.255.255.0
gateway 192.168.1.1

iface eth2 inet static
address 192.168.2.240
netmask 255.255.255.0
这似乎有效:

sed '/^iface eth1/{N;N;s/$/\ngateway 192.168.1.1/}' input.txt

-i
选项添加到
sed
以使用
sed
单向将结果保存回
input.txt

sed '
/iface eth1/ {
n
n
a\gateway 192.168.1.1
}' file

您要求使用“sed”,但“Kent”使用的是“awk”,下面是一个sed脚本,它可以满足您对示例的要求。更一般地说,sed脚本的第1行可以包含您想要的任何字符串,而sed脚本的第5行可以包含您想要的任何字符串。将以下脚本放在一个文件中,例如x.sed,不要添加任何空格或制表符

    /iface eth1/{
    n
    n
    a\
    gateway 192.168.1.1
    }
然后在命令行上像这样运行它

    sed -f x.sed "myinputfile" > "myoutputfile"

谢谢!这真的很有帮助。@user2319609很高兴能帮上忙。顺便说一句,你可以。回答得很好。我会经常使用它,就像我以前做的那样,
line_num2=$(grep-n'txt_to_find'targ_file.h | awk'{print$1}')
然后添加以获得我需要的行号!“这要有效得多。”莱维斯基感谢您的解决方案。如果要追加的文本是一个带有斜杠的变量(例如路径),那么在这种情况下,您将如何更改分隔符?Thanks@LevLevitsky更新:我发现我可以在内部的s///语句中使用逗号,比如sed'/^iface eth1/{n;n;s,$,\n'$PATH_VAR',}'谢谢,我也尝试过这样做,就像这样。。。sed-i.bak'/^iface eth1/{n;n;a\gateway 192.168.1.1}'/etc/network/interfaces。。。没有成功!!??我不知道为什么?