Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

any suggestions on how to delete last line of file?

Replies are listed 'Best First'.
Re: Deleting last line of file
by kschwab (Vicar) on Aug 07, 2002 at 20:28 UTC
    Strange that nobody has mentioned truncate. This would get rid of the overhead of rewriting the whole file.
    #!/usr/bin/perl # # given a file name as an argument, # read the file until eof, back up # one line and truncate the file there. # in short, "delete the last line of a file" # my $file=shift(@ARGV); open(FILE,"+<$file") or die; while (<FILE>) { if (eof(FILE)) { seek(FILE,-(length($_)),2) or die; truncate(FILE,tell(FILE)) or die; } } close FILE;
    This would be faster for large files if it would seek() to eof, then read backwards looking for the newline. Seemed a bit cumbersome for an example though.
Re: Deleting last line of file
by thelenm (Vicar) on Aug 07, 2002 at 17:19 UTC
Re: Deleting last line of file
by jmcnamara (Monsignor) on Aug 07, 2002 at 17:58 UTC
      I'm trying to run the shell command in my script, but for some reason, it's not working....can anyone pinpoint the problem? thanks
      my @args = qw/ perl -i -ne 'print unless eof' filename /; system(@args) == 0 or die "error with deleting last line";
        I don't think you understand what qw does. Try running this and I think you will figure it out.
        my @args = qw/ perl -i -ne 'print unless eof' filename /; print join "|", @args;

        --

        flounder


        That was just a one-liner.

        If you need to do something more sophisticated as part of a program you should try something like this.

        #!/usr/bin/perl -w use strict; # Localised in-place edit { local $^I = ''; # or use '.bak' to save a back-up local @ARGV = 'somefile'; while (<>) { print unless eof; } } __END__

        --
        John.

Re: Deleting last line of file
by Chady (Priest) on Aug 07, 2002 at 17:03 UTC
    yeah
    read the file, then print everything back without the last line.

    Tip: if you show some code, I bet you would get more results.


    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/