获取存储在变量中的文件的最后几行 [英] get last few lines of file stored in variable

查看:49
本文介绍了获取存储在变量中的文件的最后几行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取存储在变量中的文件的最后几行?在 linux 上,如果它在文件中,我会使用 tail 命令.

How could I get the last few lines of a file that is stored in a variable? On linux I would use the tail command if it was in a file.

1) How can I do this in perl if the data is in a file?
2) How can I do this if the content of the file is in a variable?

推荐答案

在某种程度上,这取决于文件有多大,以及您想要多少行.如果它将非常大,您需要小心,因为将其全部读入内存将比仅读取文件的最后一部分花费更长的时间.

To some extent, that depends how big the file is, and how many lines you want. If it is going to be very big you need to be careful, because reading it all into memory will take a lot longer than just reading the last part of the file.

如果它很小.最简单的方法可能是将它File::Slurp 放入内存中,通过记录分隔符split,并保留最后n 条记录.实际上,类似于:

If it is small. the easiest way is probably to File::Slurp it into memory, split by record delimiters, and keep the last n records. In effect, something like:

# first line if not yet in a string
my $string = File::Slurp::read_file($filename);
my @lines = split(/\n/, $string);
print join("\n", @lines[-10..-1])

如果它很大,太大而无法进入内存,那么直接使用文件系统操作可能会更好.当我这样做时,我打开文件并使用 seek() 并读取文件的最后 4k 左右,然后向后重复,直到我有足够的数据来获得我需要的记录数.

If it is large, too large to find into memory, you might be better to use file system operations directly. When I did this, I opened the file and used seek() and read the last 4k or so of the file, and repeated backwards until I had enough data to get the number of records I needed.

不是详细的答案,但问题可能更具体一些.

Not a detailed answer, but the question could be a touch more specific.

这篇关于获取存储在变量中的文件的最后几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆