#!/usr/bin/perl use strict; my @keepers; { local $/ = '***END***'; while ( ) { next unless ( /^\s*mykeyword[24]/ ); chomp; push @keepers, $_; } } print join '', @keepers; __DATA__ mykeyword1 several data lines containing junk ***END*** mykeyword2 several lines containing target data ***END*** mykeyword3 several lines containing junk ***END*** mykeyword4 again several lines containing target data ***END*** mykeyword1 several data lines containing junk ***END*** mykeyword2 several lines containing target data ***END*** mykeyword3 several lines containing junk ***END*** mykeyword4 again several lines containing target data ***END***