FAQ 5.4 How do I delete the last N lines from a file?


PerlFAQ Server

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


5.4: How do I delete the last N lines from a file?

(contributed by brian d foy)

The easiest conceptual solution is to count the lines in the file then
start at the beginning and print the number of lines (minus the last N)
to a new file.

Most often, the real question is how you can delete the last N lines
without making more than one pass over the file, or how to do it without
a lot of copying. The easy concept is the hard reality when you might
have millions of lines in your file.

One trick is to use "File::ReadBackwards", which starts at the end of
the file. That module provides an object that wraps the real filehandle
to make it easy for you to move around the file. Once you get to the
spot you need, you can get the actual filehandle and work with it as
normal. In this case, you get the file position at the end of the last
line you want to keep and truncate the file to that point:

use File::ReadBackwards;

my $filename = 'test.txt';
my $Lines_to_truncate = 2;

my $bw = File::ReadBackwards->new( $filename )
or die "Could not read backwards in [$filename]: $!";

my $lines_from_end = 0;
until( $bw->eof or $lines_from_end == $Lines_to_truncate )
print "Got: ", $bw->readline;

truncate( $filename, $bw->tell );

The "File::ReadBackwards" module also has the advantage of setting the
input record separator to a regular expression.

You can also use the "Tie::File" module which lets you access the lines
through a tied array. You can use normal array operations to modify your
file, including setting the last index and using "splice".


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Latest member

Latest Threads