Home > other >  How can I overwrite file after replace the word?
How can I overwrite file after replace the word?

Time:02-18

I want to replace the text in the file and overwrite file.

use strict;
use warnings;

my ($str1, $str2, $i, $all_line);
$str1 = "AAA";
$str2 = "bbb";

open(RP, " >", "testfile") ;

$all_line = $_;
$i = 0;
while(<RP>) {
        while(/$str1/) {
        $i  ;
        }
        s/$str1/$str2/g;
        print RP $_;
}
close(RP);

CodePudding user response:

You can access the functionality of perl -i via $^I.

use strict;
use warnings;

my $str1 = "AAA";
my $str2 = "bbb";

local $^I = '';  # Same as `perl -i`. For `-i~`, assign `"~"`.
local @ARGV = "testfile";

while (<>) {
   s/\Q$str1/$str2/g;
   print;
}

CodePudding user response:

A normal process is to read the file line by line and write out each line, changed as/if needed, to a new file. Once that's all done rename that new file, atomically as much as possible, so to overwrite the orgiinal.

Here is an example of a library that does all that for us, Path::Tiny

use warnings;
use strict;
use feature 'say';

use Path::Tiny;
    
my $file = shift || die "Usage: $0 file\n";

say "File to process:";
say path($file)->slurp;

# NOTE: This CHANGES THE INPUT FILE
#
# Process each line: upper-case a letter after .
path($file)->edit_lines( sub { s/\.\s \K([a-z])/\U$1/gs } );

say "File now:";
say path($file)->slurp;

Note: the file is edited in-place so it will have been changed after this is done.


This capability was introduced in the module's version 0.077, of 2016-02-10. (For reference, Perl version 5.24 came in 2016-08. So with the system Perl 5.24 or newer, a Path::Tiny installed from an OS package or as a default CPAN version should have this method.)

  • Related