How do I use replacement variables when doing search/replace with Regex in Perl?
I want to search a xml-file for all -tags changing the attribute enabled to false, which can be like this
<repository store-diff="true" description="ACS" name="ACS" enabled="true">
There are other tags as well having the enabled attribute so I need to search for lines starting with , which is quite easy, problem is the replacement string. I've tried this:
perl -p -e 's#^<repository.*enabled="true"#$1enabled="false"#g'
But no luck, no changes done to the file I try to change. Or, that's not true, it matches, but I'm n开发者_开发技巧ot able to change ONLY enabled="true" setting it to false, it removes the rest of the line leaving it with just enabled="false"...
Should be possible according to http://refcards.com/docs/trusketti/perl-regexp/perl-regexp-refcard-a4.pdf
#!/usr/bin/perl
use XML::Twig;
my $t = XML::Twig->new(
twig_handlers => {
# for repository tags, if it has the enabled
# attribute, set it to false.
repository => sub {
exists $_->{att}->{enabled} &&
$_->set_att(enabled => 'false');
$_->flush();
},
},
);
$t->parsefile($ARGV[0]);
$t->flush();
Seems to work for me. You may want to play with the callback for the repository tag - I'm not sure if you want to always set the enabled attribute to false, even if the attribute isn't there (delete the first line in that callback) or only if the attribute is there.
Okay, it's not a one-liner anymore. But that shouldn't be the requirement if you want it done right. Note that because this is parsing XML now, we require a well-formed XML document and we don't care if the repository tag is spread out over multiple lines, or if there is more than one on a line, or what other attributes it has, etc.
And it also doesn't fall in to your "regex" tag on your question. But that's because I think that tag is making this into an XY problem.
I haven't tested, but I believe this will work:
perl -p -e 's#^(<repository.*)enabled="true"#$1enabled="false"#g'
First, you need to have a group in order to use a backreference, so you have to parenthesize the part of the expression that you want to refer to later. In this case we want everything from <repository
all the way up to enabled...
so we enclose that bit in parentheses.
精彩评论