如何删除文件的最后5行
我有几个使用 perl 将文本打印到文件的命令。在这些 print
命令中,我有一个 if 语句,如果该语句为真,则应删除我当前正在写入的文件的最后 5 行。要删除的行数始终为 5。
if ($exists == 0) {
print(OUTPUT ???) # this should remove the last 5 lines
}
I have several commands printing text to a file using perl. During these print
commands I have an if statement which should delete the last 5 lines of the file I am currently writing to if the statement is true. The number of lines to delete will always be 5.
if ($exists == 0) {
print(OUTPUT ???) # this should remove the last 5 lines
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 Tie::File:
打印时可以使用相同的数组,但使用
push
代替:You can use Tie::File:
You can use the same array when printing, but use
push
instead:我能想到的唯一明显的方法:
截断。
至少有 5 行长,然后修剪缓冲区。
在使用缓冲区读取所有文件之前先对其进行处理,如 #2 中所示。
所有这些都非常繁琐,但这恐怕就是平面文件的本质。
华泰
Only obvious ways I can think of:
truncate.
that's at least 5 lines long, and trim the buffer.
Process all your files before reading them with a buffer as in #2
All are pretty fiddly, but that's the nature of flat files I'm afraid.
HTH
作为替代方案,打印除最后 5 行之外的整个文件:
As an alternative, print the whole file except last 5 lines:
File::ReadBackwards+
truncate
对于大文件来说是最快的,对于短文件来说可能与其他任何东西一样快。Tie::File 最慢,并且使用大量内存。避免该解决方案。
File::ReadBackwards+
truncate
is the fastest for large files, and probably as fast as anything else for short files.Tie::File is the slowest, and uses a large amount of memory. Avoid that solution.
你可以尝试这样的事情:
或者甚至缩短:
you can try something like this:
or even shortened: