Regex srch & repl only executing once

E

Ethan

This is adding more detail to my previous post. As mentioned, I'm
trying to write a simple search and replace script. My current version
is copied below. When I run it on a directory tree of files, for each
file the first occurance of the search string IS replaced, but NONE of
the others are replaced.

If I could just get it to replace all of the occurances, then I'd be
in business. Any help or information would be greatly appreciated.

Thanks!

E



sub doReplace
{
my @outLines; #Data we are going to output
my $line; #Data we are reading line by line

# Only parse files that end in .htm
if ( $File::Find::name =~ /\.htm$/ )
{
print "\nprocessing $_\n";

open (FILE, $File::Find::name ) or
die "Cannot open file: $!";

$backupFileName = $File::Find::name . ".bak";
system("cp $File::Find::name $backupFileName");

while ( $line = <FILE> )
{
print " |"; # To show that something's happening

#$line =~ s/\.jsp/.htm/; # Only works the first time
# Rest of the ".jsp"s untouched

push(@outLines, $line);
}
close FILE;

open ( OUTFILE, ">$File::Find::name" ) or
die "Cannot open file: $!";

print ( OUTFILE @outLines );
close ( OUTFILE );

undef( @outLines );
}
}
 
U

Uri Guttman

use File::Slurp ;

sub replace {

my( $file_name, $from, $to ) = @_ ;

my $text = read_file( $file_name ) ;

$text =~ s/$from/$to/g ;

rename( $file_name, "$file_name.bak" ) ;
write_file( $file_name, $text ) ;
}

untested and assumes $from is a legal regex.

uri
 
J

Joe Smith

Ethan said:
file the first occurance of the search string IS replaced, but NONE of
the others are replaced.

$line =~ s/\.jsp/.htm/; # Only works the first time

Perl will do one substitution per line because you told it to, by leaving
out the /g modifier. Check the docs for s///g and s///i.

$line =~ /s\.jsp/.htm/ig; # Do all occurrances of '.jsp' and '.JSP'

-Joe
 
E

Ethan

Thanks a lot for the help guys. I'll try those suggestions. I guess I
have to do some more reading in the docs.

E
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top