How to edit a line in txt file in perl without using a tmp file

13,827

Solution 1

Use the inplace-editing magic:

#!/usr/bin/env perl
use autodie;
use strict;
use warnings qw(all);

my $file = 'test';

# setup the inplace operation
@ARGV = ($file);
# keep backup at "$file.bak"
$^I = '.bak';

# inplace editing takes over STDIN/STDOUT
while (<>){
    print;
    if ($. == 50) {
        my $line = "testing\n";
        print $line;
    }
}

Solution 2

Read all lines, then modify the one you want to modify, and write them all back to the original file. You can optionally use modules like File::Slurp for one-line methods for reading and writing all lines.

For example:

use File::Slurp;
my @lines = read_file("yourfile.txt");
$lines[$line_number_to_modify] = "whatever\n";
write_file("yourfile.txt", @lines);
Share:
13,827
ImadT
Author by

ImadT

Updated on June 14, 2022

Comments

  • ImadT
    ImadT almost 2 years

    Possible Duplicate:
    Need perl inplace editing of files not on command line

    I have already a working script that edit my log file but i'm using a temporary file, my script working like that:

    Open my $in , '<' , $file;
    Open my $out , '>' , $file."tmp";
    
    while ( <in> ){
      print $out $_;
      last if $. == 50;
    }
    
    $line = "testing";
    print $out $line;
    
    while ( <in> ){
      print $out $_;
    }
    
    #Clear tmp file
    close $out;
    unlink $file;
    rename "$file.new", $file;
    

    I would like edit my file without creating a tmp file.