2013-04-25 55 views
5

我想在字符串匹配+ 2行后添加新行。'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 inet static 
address 192.168.2.240 
netmask 255.255.255.0 

我想找到 'IFACE eth1的' + 2行之后添加 '网关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个操作之后。与您的文件

awk -v RS="" -v ORS="\n\n" '/iface eth1/{$0=$0"\ngateway 192.168.1.1"}1' file 

: 斯蒂芬

回答

0

,如果你想添加一行到块的结尾,试试这个

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 
6

这似乎工作:

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

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

+0

非常感谢!这真的很有帮助。 – user2319609 2013-04-25 13:35:48

+0

@ user2319609很高兴能有帮助。顺便说一下,您可以[接受答案](http://meta.stackexchange.com/a/5235/181223)。 – 2013-04-25 13:38:41

+0

梦幻般的答案。将会经常使用这种方式,就像我以前用'line_num2 = $(grep -n'txt_to_find'targ_file.h | awk'{print $ 1}')'做的那样',然后添加以获得我需要的行号!这样更有效率。 – Zmart 2014-11-16 20:19:42

2

方式一:

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

你要求用“sed的”,但“肯特”使用“的awk”,这里是一个sed脚本,你想要做什么,你的榜样。更一般地说,sed脚本的第1行可以包含任何你想要的字符串,而第5行的sed脚本可以包含任何你想要的字符串。将下面的脚本放在一个文件中,比如x.sed,不要添加任何空格或制表符。

/iface eth1/{ 
    n 
    n 
    a\ 
    gateway 192.168.1.1 
    } 

然后在命令行中像这样运行它。

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

谢谢,我试图做同样的,像这样... sed -i.bak'/^iface eth1/{n; n; a \ gateway 192.168.1.1}'/ etc/network/interfaces – user2319609 2013-04-25 13:38:56

+0

...没有成功!!我不知道为什么? – user2319609 2013-04-25 13:40:14