msstein has asked for the wisdom of the Perl Monks concerning the following question:

I have spent hours on attempting to figure out why my simple search/replace string in a text file is not doing any replacing. I looked in online forums, but I believe this script is correct. Is there anything that would prevent a search/replace? My file is not read only. Also, when I print @lines to a log file, it actually prints the lines from the text file that I want to do a search/replace.

The file is called Mark.txt and only has one value "NAME". It is my test before I begin to do search/replace on a real file.

Any help would be appreciated. Thanks.

#!/usr/bin/perl use File::Find; open (logfilefsv, '>>logfsv.txt'); $file = "C:/TestPerlFSV/Mark.txt"; open(IN, "+<$file"); #my $old = "N"; #my $new = "M"; @lines=<IN>; print logfilefsv @lines; foreach $file (@lines) {s/N/M/gi;}

Replies are listed 'Best First'.
Re: Search Replace String Not Working on text file
by zentara (Cardinal) on Jun 16, 2012 at 20:23 UTC
    The problem is you are not writing the new string to the file. First you must seek to the start of the file, truncate it, then write the new string. My Mark.txt has 2 lines,NAME and ZANY, which gets changed to MAME ZAMY

    The magic of processing @ARGV can also be used, as shown in the second example.

    #!/usr/bin/perl open (logfilefsv, '>>logfsv.txt'); $file = "Mark.txt"; open(IN, "+<", $file); #my $old = "N"; #my $new = "M"; @lines = <IN>; print logfilefsv @lines; seek IN, 0, 0; # seek to top of file truncate(IN, 0); # truncate old data foreach $line (@lines) { $line =~ s/N/M/gi; print IN $line; } __END__
    Or use Magic @ARGV processing, Mark.txt is shifted in from the command line
    #!/usr/bin/perl { local ($^I, @ARGV) = ('.bak', shift ); while (<>) { $_ =~ s/M/N/gi; print "$_"; } } __END__

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: Search Replace String Not Working on text file
by stevieb (Canon) on Jun 16, 2012 at 20:33 UTC

    Try this:

    #!/usr/bin/perl use warnings; use strict; use File::Find; open my $logfilefsv, '>>', 'logfsv.txt' or die $!; my $file = "Mark.txt"; open my $in_fh, '<', $file or die $!; my @lines = <$in_fh>; close $in_fh; open my $out_fh, '>', $file or die $!; print $logfilefsv @lines; for my $line ( @lines ){ $line =~ s/N/M/gi; print $out_fh $line; }
Re: Search Replace String Not Working on text file
by Anonymous Monk on Jun 16, 2012 at 22:51 UTC
    #!/usr/bin/perl -- use strict; use warnings; use File::Slurp qw/ read_file write_file /; my $filename = 'C:/TestPerlFSV/Mark.txt'; my $lines = read_file( $filename ); $lines =~ tr/nN/MM/; write_file( $filename, \$lines ); __END__