如何在不使用tmp文件的情况下在perl中编辑txt文件中的行 [英] How to edit a line in txt file in perl without using a tmp file
本文介绍了如何在不使用tmp文件的情况下在perl中编辑txt文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经有一个可以编辑日志文件的工作脚本,但是我使用的是临时文件,我的脚本像这样工作:
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;
我想编辑文件而不创建tmp文件。
I would like edit my file without creating a tmp file.
推荐答案
使用就地编辑魔术:
#!/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;
}
}
这篇关于如何在不使用tmp文件的情况下在perl中编辑txt文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文