简体   繁体   中英

Mass Find and Replace in Multiple XML Files

I need to do a find and replace on 700+ XML files for the following:

<base>7.4</base>

needs to become

<base>7.2</base>

However, the only tool I have to use is Notepad++, and it continually crashes when I try to do the "replace in files" function. Is there another easy way to perform this mass find and replace? I'm not much of a coder, but they're all in the same folder, maybe there's a way I could use a .bat file to run through them? Any advice on what to do or how to write that would be much appreciated.

Thanks in advance,

Colette

You can download a free trial of PowerGREP from http://www.powergrep.com/

Then:

  1. Browse to the folder containing your files using the navigator on the left
  2. Select Search and replace as your action type
  3. Input <base>7.4</base> in Search box
  4. Input <base>7.2</base> in Replacement
  5. Preview your search, make sure correct files are selected
  6. Click on replace

Enter values and click on Preview

在此处输入图片说明

Preview highlights proposed changed

在此处输入图片说明

Click on 'Replace'

在此处输入图片说明

Files changed

在此处输入图片说明

XML is annoying to process, because whilst it looks like plain text - it actually isn't. It's therefore not ideal to use 'text based' pattern matching to replace it, because ... well, you can break formatting on it. Personally I'd be suggesting:

  • Download perl (like activestate community edition)
  • Install XML::Twig module (ppm install XML::Twig );
  • Use this script below - specify the files you want to change on the command line (eg thisscript.pl file1.xml file2.xml file3.xml )

Like this

#!/usr/bin/env perl

use strict;
use warnings;

use XML::Twig;

sub replace_base {
    my ( $twig, $base ) = @_;
    if ( $base->text eq "7.2" ) {
        $base->set_text("7.4");
    }
}

#iterate the files on the command line
foreach my $filename (@ARGV) {

    #set up the processor
    my $twig = XML::Twig->new(
        #output formatting
        'pretty_print'  => 'indented_a',
        #every time a 'base' element is encountered, run replace_base on it. 
        'twig_handlers' => { 'base' => \&replace_base }
    );
    #process this file
    $twig->parsefile($filename);

    #save the results to a '.new' file. 
    open( my $output, ">", "$filename.new" ) or die $!;
    print {$output} $twig->sprint;
    close($output);
}

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