Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the last line of file with data in Perl

Tags:

perl

I have a text file to parse in Perl. I parse it from the start of file and get the data that is needed.

After all that is done I want to read the last line in the file with data. The problem is that the last two lines are blank. So how do I get the last line that holds any data?

like image 429
fammi Avatar asked Mar 29 '12 08:03

fammi


2 Answers

If the file is relatively short, just read on from where you finished getting the data, keeping the last non-blank line:

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
}

If the file is longer, or you may have passed the last non-blank line in your initial data gathering step, reopen it and read from the end:

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/;
like image 135
ysth Avatar answered Sep 19 '22 02:09

ysth


perl -e 'while (<>) { if ($_) {$last = $_;} } print $last;' < my_file.txt
like image 22
slipset Avatar answered Sep 19 '22 02:09

slipset