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

标签 perl file edit

<分区>

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

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

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 文件的情况下编辑我的文件。

最佳答案

读取所有行,然后修改你要修改的那一行,全部写回原文件。您可以选择使用像 File::Slurp 这样的模块用于读取和写入所有行的单行方法。

例如:

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

关于perl - 如何在不使用 tmp 文件的情况下在 perl 中编辑 txt 文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971449/

相关文章:

regex - (?^ :…) mean in the string form of a Perl qr//Regex? 中的插入符号 ^ 是什么

perl - 找不到信号处理程序

python - 在文件对象上频繁调用 write() 并添加少量内容是否不好?

c - 修改c中文件的现有内容

c++ - 如何使用 C++ 删除/更新 txt 文件中的特定数据?

perl - 在 Perl 中枚举所有可能长度的有序标记

mysql - fork 还是不 fork ?

Linux 终端 : how to copy output to a file and print at terminal simultaneously?

java - 如何用 java 读取/写入 NetBeans 项目本身中的文件

c++ - 编辑控制文本溢出