#!/usr/bin/perl # https://perlmonks.org/?node_id=1216436 use strict; use warnings; my @sections; while( ) { if( /^Title/ ) { unshift @sections, [ tell(DATA) - length, length ]; } elsif( @sections ) { $sections[0][1] += length; } } for ( @sections ) { seek DATA, $_->[0], 0 or die; local $/ = \$_->[1]; print scalar ; } __DATA__ Title 1 Line of text A Line of text B Title 2 Line of text C Title 3 Title 4 Line of text D