如何在不使用tmp文件的情况下在perl中编辑txt文件中的一行

Ima*_*adT 2 perl file edit

可能重复:
需要perl就地编辑不在命令行上的文件

我已经有一个编辑我的日志文件的工作脚本,但我正在使用一个临时文件,我的脚本像这样工作:

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;
Run Code Online (Sandbox Code Playgroud)

我想编辑我的文件而不创建一个tmp文件.

Mor*_*kus 7

读取所有行,然后修改要修改的行,并将它们全部写回原始文件.您可以选择使用File :: Slurp等模块来读取和写入所有行的单行方法.

例如:

use File::Slurp;
my @lines = read_file("yourfile.txt");
$lines[$line_number_to_modify] = "whatever\n";
write_file("yourfile.txt", @lines);
Run Code Online (Sandbox Code Playgroud)


cre*_*ive 5

使用inplace-editing魔术:

#!/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;
    }
}
Run Code Online (Sandbox Code Playgroud)