Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'sed' : How to add new line after string match + 2 lines

Tags:

sed

I would like add a new line after string match + 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 found 'iface eth1' + 2 lines.

example: what I need to get after execute 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, append line after specific string, etc. but not combine this 2 operation. Steph

like image 605
user2319609 Avatar asked Apr 25 '13 12:04

user2319609


3 Answers

This seems to work:

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

Add the -i option to sed to save the result back to input.txt.

like image 98
Lev Levitsky Avatar answered Nov 18 '22 12:11

Lev Levitsky


One way using sed:

sed '
/iface eth1/ {
n
n
a\gateway 192.168.1.1
}' file
like image 40
Steve Avatar answered Nov 18 '22 11:11

Steve


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

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

Then run it like this on the command line.

    sed -f x.sed "myinputfile" > "myoutputfile"
like image 1
Marichyasana Avatar answered Nov 18 '22 11:11

Marichyasana