'sed': how to add a new line after matching a line + 2 lines

I would like to add a new line after matching the line + 2 lines.

Here is my 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

I want to add 'gateway 192.168.1.1' after I find 'iface eth1' + 2 lines.

example: what do I need to get after running the sed command

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

I know how to find and move 2 lines after, add a line after a certain line, etc., but not combine this operation 2. Stef

+5
source share
4 answers

It works:

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

Add a parameter -ito sedto return the result to input.txt.

+6
source

One way sed:

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

, :

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
0

You asked to use "sed", but "Kent" uses "awk", here is a sed script that does what you want for your example. To be more general, line 1 sed script can contain any desired line, and line 5 sed script can contain any desired line. Put the following script in the file, say x.sed, do not add spaces or tabs.

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

Then run it like on the command line.

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

All Articles