$ perl -Mstrict -Mwarnings -Mautodie -le ' my $file = "pm_1053380_data.txt"; my ($match, $before) = @ARGV; my @previous; open my $fh, "<", $file; while (<$fh>) { chomp; if ($_ eq $match) { print $previous[0]; } push @previous, $_; shift @previous if @previous > $before; } ' line4 2 line2