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!"; }

In reply to Re: How to reorder a text file by rminner
in thread How to reorder a text file by hennesse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.