use strict; use warnings; my @wantedLines = grep { m{^fileid} .. m{^-----} and m{pattern} } <>; print for @wantedLines; #### $ cat spw765108.log a line another line fileid 123 some data a pattern we want some more data another wanted pattern yet more data ----- another line a pattern outside our bounds last line $ #### $ ./spw765108 spw765108.log a pattern we want another wanted pattern $