用Perl读取文件的最后一行数据

sqserrrh  于 2022-11-15  发布在  Perl
关注(0)|答案(7)|浏览(335)

我有一个文本文件要用Perl解析。我从文件的开头解析它,并获得所需的数据。
在完成所有这些之后,我想读取文件中最后一行的数据。问题是最后两行是空的。那么我如何获得最后一行的数据呢?

ljsrvy3e

ljsrvy3e1#

如果文件相对较短,只需从获取数据的位置继续读取,保留最后一行非空行:

use autodie ':io';
open(my $fh, '<', 'file_to_read.txt');
# get the data that is needed, then:
my $last_non_blank_line;
while (my $line = readline $fh) {
    # choose one of the following two lines, depending what you meant
    if ( $line =~ /\S/ ) { $last_non_blank_line = $line }  # line isn't all whitespace
    # if ( line !~ /^$/ ) { $last_non_blank_line = $line } # line has no characters before the newline
}

如果文件较长,或者您可能在初始数据收集步骤中跳过了最后一个非空行,请重新打开文件并从末尾开始读取:

my $backwards = File::ReadBackwards->new( 'file_to_read.txt' );
my $last_non_blank_line;
do {
    $last_non_blank_line = $backwards->readline;
} until ! defined $last_non_blank_line || $last_non_blank_line =~ /\S/;
9wbgstp7

9wbgstp72#

perl -e 'while (<>) { if ($_) {$last = $_;} } print $last;' < my_file.txt
lsmepo6l

lsmepo6l3#

可以按以下方式使用模块File::ReadBackwards

use File::ReadBackwards ;
$bw = File::ReadBackwards->new('filepath') or
    die "can't read file";
while( defined( $log_line = $bw->readline ) ) {
    print $log_line ;
    exit 0;
}

如果它们是空的,只需检查$log_line是否与\n匹配;

w9apscun

w9apscun4#

如果文件很小,我会把它存储在一个数组中并从末尾读取。如果文件很大,使用File::ReadBackwards模块。

ogsagwnx

ogsagwnx5#

下面是我的命令行Perl解决方案的变体:

perl -ne 'END {print $last} $last= $_ if /\S/' file.txt
cwtwac6a

cwtwac6a6#

没有人提到Path::Tiny。如果文件大小相对较小,您可以这样做:

use Path::Tiny;

my $file = path($file_name);
my ($last_line) = $file->lines({count => -1});

CPAN页面。
请记住,对于大文件,正如@ysth所说,最好使用File::ReadBackwards

6ss1mwsb

6ss1mwsb7#

有时候从perl代码运行shell命令对我来说更舒服。所以我更喜欢下面的代码来解决这种情况:
$result='tail -n 1 /路径/文件';

相关问题