using perl, how to select last 2 lines in the case of each row has same word?

前端 未结 2 1973
深忆病人
深忆病人 2021-01-29 11:45
Bini  --  -21.89753  -20.47853  -20.27835  -18.34952  -16.23454

Bini  --  -16.89753  -14.47853  -13.27835  -12.34952  -11.23454

Bini  --  -10.09014  

2条回答
  •  执念已碎
    2021-01-29 12:01

    ••• NOTE •••• The input file here is specific to your more recent, blocked, question (using perl, how to select last 2 lines in the case of each row has same word?(re-questioned..)) and as such will only work with that input.

    This is the input you recently provided:

    Bini  --  -10.09014  
    
    cidi
    
    Bini  --  -21.89753  -21.47853  -20.27835  -20.34952  -17.23454
    
    Bini  --  -16.89753  -12.47853  -11.27835  -11.34952  -10.23454
    
    Bini  --  -09.09014  
    
    light is 3.4
    

    This will achieve exactly what you want (i.e. extract the last two elements from the second-to-last line starting with 'Bini' and the last element from the last line ending in 'Bini') , but no more ...

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my $file = 'location/of/your/file.txt';
    open my $input, '<', $file or die "Can't write to $file: $!";
    
    my $line = 0;
    my (@element1, @element2, @element3);
    while (<$input>){ 
        chomp;
        next if ($_ =~ /^\s*$/); # skips a line of input if the line is blank
            if ($_ =~ /^Bini/) { # if the line starts with Bini
                $line++; # Add 1 to count variable
                my @split = split('\s+'); # split by spaces
                if ($line == 3) { # if the line number = 3 (i.e. second to last)
                    push @element1, $split[-1]; # add the last element of split (-10.234...) to @element1
                    push @element2, $split[-2]; # # add the second-to-last element of split to @element2
                }
                elsif ($line == 4) { # if the line number is 4 (last line starting with Bini
                    push @element3, $split[-1]; # # add the last element of split to @element1
                }
            }
    }
    
    print "$element3[0]\t$element1[0]\t$element2[0]\n";
    

    Output:

    -09.09014   -10.23454   -11.34952
    

提交回复
热议问题