简体   繁体   中英

Changing multiple lines of XML file using Perl one-liner

I am trying to change XML files using a Perl one-liner. The XML file is set up as

<NameBool name="Hardware Enabled">
    <BoolConfig>
       <value>false

I need to change the file to true. I have written a one-liner that seems to execute, but it never actually changes the file. What am I doing wrong?

Code

perl -p0777i -e 's/<NamedBool name=\"HardwareEnabled\">\n<BoolConfig>\n<value>false/<NamedBool name=\"HardwareEnabled\">\n<BoolConfig>\n<value>true/m' filename*

Why do you need a one-liner? Is it really so complicated to write a proper (small) script that would be easier to debug and maintain?

Anyway, provided you lines are long enough ;--)

perl -MXML::Twig -e'XML::Twig->new( twig_handlers => { q{NameBool[@name="Hardware Enabled"]/BoolConfig/value} => sub { $_->set_text( "false")->flush; } }, keep_spaces => 1)->parsefile_inplace( "to_change.xml")'

As was said in the comments above, you are not taking into account that there is indentation in your files. If there is not much else in there, how about this very simple regex:

s/\bfalse\b/true/

If however there are other occurrences of false , you will have to stick to your regex, but add whitespace. You could keep indentation and such, by doing it like this:

s/(<NameBool name="Hardware Enabled">\s+<BoolConfig>\s+<value>)false/${1}true/m

Note that there were two differences between your example data and your regex:

  • example: NameBool , regex: NamedBool
  • example: "Hardware Enabled" , regex: "HardwareEnabled"

Take a look at http://regex101.com/r/wZ8bN5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM