in reply to New Line at End File

Here's a way to do it without reading the whole file in first...

#!/usr/bin/perl use strict; use Fcntl qw(SEEK_END SEEK_CUR); my $f = shift; open F, "+<", $f or die "Couldn't open $f: $!\n"; seek F, -1, SEEK_END; seek F, -2, SEEK_CUR while (getc(F) eq "\n"); truncate F, tell F;
-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re: Re: New Line at End File
by BrowserUk (Patriarch) on Dec 10, 2002 at 05:10 UTC

    It's nit time:^) The only question is the nit the code or me but...

    Doesn't the use of -2, make this non-portable? Wouldn't this only work on DOSish systems? How about -length "\n" instead of -2?


    Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
    Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
    Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
    Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

      The only question is the nit the code or me but...

      Personally, I think that nit should be with the "OS"... but, yeah. You got me. ;-)

      -sauoq
      "My two cents aren't worth a dime.";
      
Re: Re: New Line at End File
by jmcnamara (Monsignor) on Dec 10, 2002 at 11:29 UTC

    This also strips the last newline from the file.

    Changing the last line to the following should fix it:

    my $pos = tell F; truncate F, 1 +$pos if $pos > 1;

    --
    John.

      This also strips the last newline from the file.

      Of course it does. That's exactly what was asked for. The OP read, "Is there an easy way to determine if there are new line characters at the bottom of a file, and if so delete them?" He didn't ask how to delete all but one newline or how to remove blank lines.

      -sauoq
      "My two cents aren't worth a dime.";
      

        You are right. I stand corrected.

        --
        John.