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
In reply to Re^3: replace text
by mtmcc
in thread replace text
by dawg31wh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |