What you have done wrong is you're trying to parse XML with a regular expression. This is a bad idea - it sometimes works, but it makes brittle code. XML has a specification that allows for linefeeds, whitespace and tag nesting - all things that regex handle very badly.
The real answer is 'use a parser'.
I would suggest perl
and XML::Twig
as options - there are others though:
use strict;
use warnings;
use XML::Twig;
my $twig = XML::Twig->new(
'pretty_print' => 'indented',
'twig_handlers' => {
'File' => sub { $_->set_att( 'value', 'true' ) }
}
);
$twig->parsefile('config.xml');
$twig->print;
I have made certain assumptions about the content of your XML - if you're prepared to give a more extensive example, I'll double check and make sure this works as indented.
Edit:
Based on the snippet you posted - that isn't valid XML, so disregard the above. I would still suggest though that you don't use something that looks a bit like XML, called output.xml
because that's a road to all sorts of pain and woe.
My code above will work with:
<xml>
<File value="false"/>
<File value="false"/>
<File value="false"/>
<File value="false"/>
<File value="false"/>
<File value="false"/>
<File value="false"/>
</xml>
You can check XML validity here: http://www.xmlvalidation.com/index.php?id=1&L=0
If we leave aside the fact that it's not XML - this works:
#!/usr/bin/perl
use strict;
use warnings;
while ( <DATA> ) {
#amend just line 7
if ( $. == 7 ) { s,<Filevalue=".*">,<Filevalue="true">,; }
print;
}
__DATA__
<Filevalue="false">
<Filevalue="false">
<Filevalue="false">
<Filevalue="false">
<Filevalue="false">
<Filevalue="false">
<Filevalue="false">
Which you can one-liner by:
perl -nle 'if ( $.==7) {s,<Filevalue=".*">,<Filevalue="true">,g;} print;' notxml.txt
config.xml
. That doesn't look like valid XML? – Sobrique May 07 '15 at 10:37