Jimmy Zoto
Jimmy Zoto

Reputation: 1763

Perl multiline regex replace from CLI

I want to permanently enable a Linux repo from the command line in a file that contains the definitions of multiple repos. So the file looks something like :

[repo-first]
some config line
another config line
enabled=0
more config lines

[repo-second]
some config line
another config line
enabled=0
more config lines

I want to be able to selectively set 'enable=0' to 'enable=1' based on the repo name.

There seem to be multiple ways of sucking in the file and/or ignoring the line separator including -p0e, -0777, "BEGIN {undef $}...". My best guess so far is something like :

perl -0777 -e -pi "BEGIN { undef $/ } s/(\[repo\-first\]\n(.*\n)*?enabled\=)0/$1\1/mg" /etc/yum.repos.d/repo-def-file

But naturally, this doesn't work. Ideas?

Upvotes: 1

Views: 125

Answers (2)

Borodin
Borodin

Reputation: 126762

As explained, a regex is generally the wrong approach, but it does have the advantage of retaining the order and structure of the file

So if you must, then this will do the job

perl -0777 -i -pe's/\[repo-first\][^[]+enabled=\K\d+/1/' repo-def-file

Upvotes: 1

Borodin
Borodin

Reputation: 126762

It would be much more convenient to use a module, such as Config::Tiny

use strict;
use warnings;

use Config::Tiny;

my $conf = Config::Tiny->read( 'repo-def-file' );
$conf->{'repo-first'}{enabled} = 1;
$conf->write( 'repo-def-file' );

Upvotes: 3

Related Questions