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
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
.
One way using sed
:
sed '
/iface eth1/ {
n
n
a\gateway 192.168.1.1
}' file
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With