1

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?

2
  • 1
    If the repo configs are separated with a blank line, you can use paragraph mode to good effect -00. E.g. perl -00 -pi -e"next unless /\Q[repo-first]/; s/^enabled=\K0/1/m;" file. Though I have to say that Borodin's answer will work much better. Commented Aug 2, 2015 at 12:50
  • 2
    Also -0777 and BEGIN { undef $/ } are mutually exclusive, as they do the same thing. Commented Aug 2, 2015 at 12:51

2 Answers 2

3

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' );
Sign up to request clarification or add additional context in comments.

3 Comments

That's easy, but this is for a system setup script in a hosted environment, so, unfortunately, it has to be command line.
@JimmyZoto perl /path/to/script (even in a shared hosting environment you can write to files, can't you?) If that doesn't work, perl -MConfig::Tiny -we'my $conf = Config::Tiny->read('repo-def-file'); $conf->{'repo-first'}{enabled} = 1; $conf->write('repo-def-file'); Alternatively, store the argument to -e in a heredoc in the setup script.
Probably. But it requires a dependency (which my distro, barebones CentOS, doesn't have by default) and it's actually longer on the command line by quite a bit. In code, using Tiny is much more readable, but for this particular case, I think the regex is preferable.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.