The following will do what you want if you're using Bourne shell: sed -n -e ' /CZECH/{ : loop p n /PERU/!b loop } ' filename Thanks to Maarten Litmaath for posting the original suggestion from which this is derived. Patrick Hyland.