2012-12-20 44 views
2

可能重複:
Need perl inplace editing of files not on command line如何編輯在Perl的txt文件中的行不使用tmp文件

我已經是編輯我的日誌文件中的工作劇本,但我」使用臨時文件男,我的劇本那樣工作:

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; 

我想編輯我的文件,而無需創建TMP文件。

回答

5

使用就地編輯魔術:

#!/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; 
    } 
} 
7

閱讀所有行,然後修改要修改的行,並將它們全部寫回原始文件。您可以選擇使用像File::Slurp這樣的模塊來實現單行方式讀取和寫入所有行。

例如:

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