2013-04-25 71 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

相關問題