FreeKB - Match last occurrence of a line in a file in Perl
Match last occurrence of a line in a file in Perl

Home > Search


Let's say foo.txt has numerous lines of identical text, like this.

some random text
Hello World
some other random text
Hello World
even more random text
Hello World

 

Using a while loop and the $. operator, we can append each line number to the file.

open(FH, "<", "foo.txt");

while (my $line = <FH>) {
  print "$. $line";
}

close FH;

 

This will identify that line 6 is the last line that contains Hello World.

1 some random text
2 Hello World
3 some other random text
4 Hello World
5 even more random text
6 Hello World

 

We can then use this markup to store the last line into a variable, most appropriate called $last_line;

open(FH, "<", "foo.txt");

while (my $line = <FH>) {
  if ($line =~ /Hello World/) {
    $last_line = "$. $line";
  }
}

close FH;

my @last_line = split/ /, $last_line;

print "Line $last_line[0] in foo.txt contains the last occurrence of $last_line[1]\n";

 

Running this script will produce the following output.

Line 6 in foo.txt contains the last occurrence of Hello World

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 3b6d0 in the box below so that we can be sure you are a human.




Comments