I need a simple Perl script to replace strings in an XML file

I need a simple Perl script to replace strings in an XML file.  Machine: Windows Server 2003 with ActivePerl 5.8.6

We need to manipulate an XML file for IIS config offline and the VB code needed to search and replace one string in the file is hideous and buggy.  Is there a simple Perl script to read in a file, search for "My Text-2", replace that with "My Text" and write the file back to either the original or a separate file?

Perl has to be the easiest language for this...prove me right!

Simplest, fastest one wins...
LVL 1
itcs-cssAsked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
local $^I=".bak";
0
 
rivusglobalCommented:
Hi itcs-css,

Try this:

$filename = "filename";
$search = "My Text-2";
$replace = "My Text";

die unless open( FH, "<$filename" );
die unless open( OUT, ">$filename.tmp" );
while $line ( <FH> ) {
    $line =~ /$search/$replace/;
    print OUT $line;
}
close( FH );
close( OUT );
unlink( $filename );
rename "$filename.tmp", $filename;
   
0
 
ozoCommented:
{local @ARGV=("filename"); local $^I="";
  while( <> ){
    s/My Text-2/My Text/g;
    print;
  }
}
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
itcs-cssAuthor Commented:
Thanks for the quick response...

Unfortunately the code is giving syntax errors for lines 7 near "while $line", and 10 near "}", and complains that a scalar is found where operator expected on line 8.

Any chance someone could fix this?
0
 
itcs-cssAuthor Commented:
Hi ozo,

Thanks for the quick response...

Unfortunately for yours I get...

Can't do inplace edit without backup at "blah blah.pl" line 2

Any ideas?
0
 
rivusglobalCommented:
whoops sorry about that, try this:

$filename = "filename";
$search = "My Text-2";
$replace = "My Text";

die unless open( FH, "<$filename" );
die unless open( OUT, ">$filename.tmp" );
while( <FH> ) {
    $line = $_;
    $line =~ /$search/$replace/;
    print OUT $line;
}
close( FH );
close( OUT );
unlink( $filename );
rename "$filename.tmp", $filename;
0
 
manav_mathurCommented:
Im not sure if im missing something, but cannot this go straight on the command line...

perl -i.bak -pe "s/My Text-2/My Text/g" yourfilename
0
 
ozoCommented:
it can
0
 
itcs-cssAuthor Commented:
Thanks for the help guys.

I will give out the points here in a minute...

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.