简体   繁体   English

如何在Windows上使用裸露的Perl读取文件的最后一行?

[英]How do I read the last line of a file with a bare Perl on Windows?

I need to read only the last line of a file, without using File:ReadBackwards module as it is not installed on my remote server(windows) where I need to execute the script. 我只需要读取文件的最后一行,而无需使用File:ReadBackwards模块,因为它没有安装在需要执行脚本的远程服务器(windows)上。 Kindly suggest the most efficient way to read only the last line. 请提出一种最有效的方法来仅读取最后一行。

This answer does not work on Windows. 此答案在Windows上不起作用。


If this is a one-off thing, simply do a system call and use tail . 如果这是一次性的事情,只需执行系统调用并使用tail

my $last_line = `tail -n 1 $filename`;

If you need to do this a lot, think about installing into a local-lib on the remote machine, or fatpacking File::ReadBackwards into your script before you deploy it. 如果您需要做很多事情,请考虑在部署之前将其安装到远程计算机上的本地库中,或 File :: ReadBackwards打包到脚本中。

You are in windows. 您在Windows中。 I don't know what are the inbuild command for windows but you try something like as follows 我不知道Windows的内置命令是什么,但是您尝试如下操作

Iterate the file handler with while loop and store the output in variable then print it 使用while循环迭代文件处理程序,并将输出存储在变量中,然后打印

open my $fh ,"<","file.txt";
my $last_line;
$last_line = $_,while (<$fh>);
print $last_line;

or else try the follow but these are consume more memory. 否则请尝试以下操作,但是这些会消耗更多的内存。

open my $fh ,"<","file.txt" or die "error opening $!";
my @ar = <$fh>;
print $ar[-1];

Or else 要不然

open my $fh ,"<","file.txt" or die "error opening $!";
my @ar = <$fh>;
print pop @ar;

If you know something about the files (if the lines are relatively equal lengths, or if each line is at most X bytes, or whatever) you might be able to do something with seek. 如果您对文件有所了解(如果各行的长度相对相等,或者每行最多为X个字节,等等),您可能可以对seek做一些事情。 For example, if the last line is at most 40 bytes or so, you can do the below. 例如,如果最后一行最多为40个字节左右,则可以执行以下操作。 If you know the file is 100 MB (using File::stat, which is core) you could average the first 10 lines and see how many bytes they are, and maybe multiply that by 5 just in case and seek back that far and then do the loop. 如果您知道文件为100 MB(使用File :: stat,这是核心),则可以对前10行取平均并查看它们的字节数,然后乘以5以防万一,然后再找回远处做循环。 You might have to read 15 or 20 lines, but that's not bad. 您可能需要阅读15或20行,但这还不错。

open(my $input,"input2.txt")||die "can't open the file";

my $last_line;
seek ($input, -50, 2);
while(<$input>)
{
    $last_line = $_;
}

print "$last_line\n";

I found the following here . 我在这里找到以下内容。

Try this on for size: 尝试以下尺寸:

system tail => -1 => $file;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM