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

被刻印的时光 ゝ 提交于 2019-12-11 02:29:40

问题


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.


回答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;
    }
}



回答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);


来源:https://stackoverflow.com/questions/13971449/how-to-edit-a-line-in-txt-file-in-perl-without-using-a-tmp-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!