我有一个要在Perl中解析的文本文件,我从文件的开头解析它并获取所需的数据。
完成所有这些后,我想用文件读取文件中的最后一行。问题是最后两行是空白的。那么我如何获得包含任何数据的最后一行。
答案 0 :(得分:7)
如果文件相对较短,只需从完成数据的地方继续阅读,保留最后一个非空行:
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/;
答案 1 :(得分:4)
perl -e 'while (<>) { if ($_) {$last = $_;} } print $last;' < my_file.txt
答案 2 :(得分:2)
您可以通过以下方式使用模块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
匹配;
答案 3 :(得分:0)
如果文件很小,我会将它存储在一个数组中并从末尾读取。如果它很大,请使用File :: ReadBackwards模块。
答案 4 :(得分:0)
这是我的命令行perl解决方案的变体:
perl -ne 'END {print $last} $last= $_ if /\S/' file.txt
答案 5 :(得分:0)
没有人提到Path::Tiny
。如果文件大小相对较小,您可以这样做:
use Path::Tiny;
my $file = path($file_name);
my ($last_line) = $file->lines({count => -1});
请记住大文件,正如@ysth 所说最好使用File::ReadBackwards
。差异可能很大。