in reply to replace text

One or two suggestions:

#!/usr/bin/perl use warnings; use strict; my $found = 0; my $line = 0; while (1) { system("clear"); print "Enter P to process a file or Q to quit: "; chomp( my $ans=<STDIN> ); if ( $ans =~ /^p$/i ) { print "What file would you look to open? "; chomp( my $file=<STDIN> ); die "Could not open file: $file!\n\n" if !-e $file; open(my $fh, '<', $file); print "What text would you like to search for? "; chomp( my $find=<STDIN> ); print "What text would you like it replaced with? "; chomp( my $replace=<STDIN> ); open (NEW, ">", "new.txt"); while ( <$fh> ) { if ($_ =~ /$find/i ) { $line = $_; $line =~ s/$find/$replace/g; print NEW "$line"; $found += 1; } else { print NEW "$_"; } } print STDERR "\nFound and replaced $found copies of \"$find\" +with \"$replace\".\n" if $found > 0; print STDERR "\n$found copies of \"$find\" found in $file.\n" +if $found == 0; unlink "new.txt" if $found == 0; sleep (5); } elsif ( $ans =~ /^Q$/ ) { exit(); } close NEW; $found = 0; }

Michael

Replies are listed 'Best First'.
Re^2: replace text
by dawg31wh (Initiate) on Jul 11, 2013 at 17:48 UTC

    Michael Thanks your suggestions work.

      Glad to be able to help.

      By the way, if you really want to replace the original file with the new changes, you could push the new lines to an array, close the input file, and write over it with the new array, maybe something like this:

      #!/usr/bin/perl use warnings; use strict; my $found = 0; my $line = 0; my @newFile = (); while (1) { system("clear"); print "Enter P to process a file or Q to quit: "; chomp( my $ans=<STDIN> ); if ( $ans =~ /^p$/i ) { print "What file would you look to open? "; chomp( my $file=<STDIN> ); die "Could not open file: $file!\n\n" if !-e $file; open(my $fh, '<', $file); print "What text would you like to search for? "; chomp( my $find=<STDIN> ); print "What text would you like it replaced with? "; chomp( my $replace=<STDIN> ); #open (NEW, ">", "new.txt"); while ( <$fh> ) { if ($_ =~ /$find/i ) { $line = $_; $line =~ s/$find/$replace/g; push(@newFile,"$line"); $found += 1; } else { push(@newFile, "$_"); } } open (WIPEORIGINAL, ">", "$file"); for (@newFile) { print WIPEORIGINAL "$_"; } close WIPEORIGINAL; print STDERR "\nFound and replaced $found copies of \"$find\" +with \"$replace\".\n" if $found > 0; print STDERR "\n$found copies of \"$find\" found in $file.\n" +if $found == 0; @newFile = (); $found = 0; sleep (5); } elsif ( $ans =~ /^Q$/ ) { exit(); } # close NEW; }

      --Michael