use warnings; use strict; my $i = -1; my @chunks; while () { ++$i if /^\[.+?\] \[[A-Z]+\]/; $chunks[$i] .= $_ if $i >= 0; } print grep { /DBPoolSQLException/ } @chunks;