#!/Perl/bin/perl -w open(INFILE, "< file.log") or die "Cant open file : $!"; open(OUT, "> results.txt") or die "Cant open new file : $!"; use strict; my $pattern = "Error while detecting new item"; my @history = ("\n") x 3; while () { print OUT @history if /$pattern/; push @history, $_; shift @history; } print $.; close INFILE; close OUT; exit; #### results.txt matched line 1 matched line 2 matched line 3 results of first match matched line 1 matched line 2 matched line 3 results of second match and so on...