in reply to How to reorder a text file

There are already plenty good answers. Adding another answer for the fun of it. This answer uses the CPAN Module File::ReadBackwards.

It reads the file backwards and prints out the results every time a block is complete (Title line found). Memory usage should therefore be low. Exit if the expected "Title" line is not found for $MAX_LENGTH chars. Otherwise large input files without "Title" lines could still cause massive memory usage.

Caveat: the length is only updated every time a "line" has been read. If there is a huge input line (e.g. several gigabytes without newline), this programm will still crash and burn :).

use strict; use warnings; use File::ReadBackwards; my $MAX_LENGTH = 1_000_000; my $infile = shift @ARGV; die "'$infile' is not a file!" unless (-f $infile); my $bw = File::ReadBackwards->new( $infile ) or die "can't read '$infile' $!"; my (@block, $length, $line); while( defined( $line = $bw->readline ) ) { unshift @block, $line; $length += length $line; if ($line =~ m/^Title\b/) { print @block; @block = (); $length = 0; } if ($length >= $MAX_LENGTH) { die "$length chars read, without finding a 'Title' line\n". "Input file '$infile' probably has the wrong file format." +; } } if (@block) { print STDERR scalar(@block) ." lines not printed out yet!"; }