gama larios
gama larios

Reputation: 31

Is there a function or arrangement that returns the penultimate line of a txt file?

There are three or more lines that the document brings, that is the size of the list doc03053220190606125901(1).txt.total.txt

Tamafo total: 512 MB
Total 43046✔
Total 14758

doc05889820190606122032(2).txt.total.txt

Tamano total: 1.0 GB
Total 156253✔
, Total 761273

of the txt documents I want to print only line one before the last

I tried to apply the pop function without the push function to run again pop and bring me the penultimate line or at the time of printing I give an example


my @arreglo = $row;
pop @arreglo "$files\n"
print @arreglo[-1]"\n"; 

foreach $filename (@FILES) {

    ## muestra el contenido de la variable
    print $filename, "\n"; 
    ## abre el archivo o manda una excepcion 
    open(my $file, '<', $filename) 
        or die "Could not open file '$filename' $!";

    while (my $row = <$file>) {

        chomp $row;   
        print ("$row\n");

    }

Upvotes: 0

Views: 73

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263257

Requirement: Print the second to last line of input.

The obvious solution is to slurp all of input into an array, but if the input is too large that's going to waste memory. You should also handle the case where input is less than two lines.

My solution: Keep an array that holds just the last two lines. You won't know that you've seen the second to last line until you've reached the end of the input.

#!/usr/bin/perl

use strict;
use warnings;

my @last2 = ();
while (<>) {
    if (scalar @last2 >= 2) {
        shift @last2;
    }
    push @last2, $_;
}
if (scalar @last2 >= 2) {
    print $last2[-2];
}
else {
    die "Not enough input\n";
}

Upvotes: 1

lordadmira
lordadmira

Reputation: 1832

Gama, there is no need for a complex script here. The Unix tail command will do it for you.

@last_two_lines = `tail -n2 $filename`;
print $last_two_lines[0];

Upvotes: 1

Related Questions