Perl (Scripting) - Match last occurrence of a line in a file

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
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
Did you find this article helpful?
If so, consider buying me a coffee over at