Skip to content
Advertisement

sed command to replace all last lines with some new multi line strings after getting second pattern

I want to write a program to change systems ip address from dhcp/static to static only. my original file’s contents will be either this

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;
addresses1=192.168.1.10;24;192.168.1.1;

or it may be like this,

some initial text

[ipv6]
method=auto

[ipv4]
method=auto

Now, i want to change after [ipv4] pattern, so that after editing my file should looks like this

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;

Advertisement

Answer

Here’s a Perl solution. It sets the record delimiter to 2 newlines, so paragraphs are read. If the paragraph contains [ipv4], replace the input with the replacement. Replace data with the name of your file, or with "$@" and make it into a shell script. Add -i as an option to Perl if you want to overwrite files (don’t do that until you’ve tested it).

perl -pe '
my $replacement = qq"[ipv4]n" .
                    "method=staticn" .
                    "dns=8.8.8.8;4.4.4.4;n" .
                    "addresses1=192.168.1.20;24;192.168.1.1;nn";
$/ = "nn";
$_ = $replacement if (m/^[ipv4]$/m);' data

There are many alternative ways of writing that code; I make no claims other than “it works for me”.

Given the text of your question as the input, the output is:

I want to write a program to change systems ip address from dhcp/static to static only. my original file's contents will be either this

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;

or it may be like this,

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;

Now, i want to change after [ipv4] pattern, so that after editing my file should looks like this

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;
Advertisement