in reply to Printing line before matching expression

G'day rm,

Welcome to the monastery.

You just need to keep a sufficient history of previous lines so that you go back to the previous nth line. Here's one way to do it:

$ 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

The input file I used:

$ cat pm_1053380_data.txt line1 line2 line3 line4 line5

Notes:

-- Ken