use strict; use warnings; my $last_line=''; open (DIFFR, "/tmp/log.diff") or die "Can't open /tmp/log.diff: $!"; while () { chomp; if (/\bERROR\b/) { print CSVFILE $last_line; print CSVFILE "$line,"; } $last_line = $_; }