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

Hello Monks,

I am trying to achieve a very simple task, or so I thought till I started trying to accomplish it. I would like to read a file and delete all of the content that appears before a specific line.
Any ideas on how I could achieve this goals?

Thank you very much.

Replies are listed 'Best First'.
Re: Seek and delete
by ikegami (Patriarch) on May 22, 2008 at 09:36 UTC

    The simplest way is to copy the desired lines to a temporary store (an array or a temporary file) then write the contents of the store over the existing file (or rename the temporary file).

    One specific implementation:

    perl -i -ne"next if $.<100; print" file
Re: Seek and delete
by apl (Monsignor) on May 22, 2008 at 09:54 UTC
    I am trying to achieve a very simple task, or so I thought till I started trying to accomplish it.
    Could we see what you tried to implement? What was difficult about this "simple task"?
Re: Seek and delete
by pc88mxer (Vicar) on May 22, 2008 at 13:14 UTC
    Here's a solution using Tie::File:
    use Tie::File; tie @array, ’Tie::File’, "filename" or die "tie failed: $!"; # remove the first 100 lines: splice(@array, 0, 100); untie @array;
    If you don't know the exact line number, then you could do something like this:
    tie @array, 'Tie::File', "filename" or die ...; my $i; for (@array) { if (m/some regex/) { last } $i++; } splice(@array, 0, $i);
Re: Seek and delete
by toolic (Bishop) on May 22, 2008 at 16:32 UTC
    If you are just doing quick and dirty stuff on *nix, there's always sed.

    This deletes the 1st 5 lines of a file:

    sed 1,5d file.txt

    This deletes the all lines of a file up until the line including the string "end_of_header" (inclusive):

    sed 1,/end_of_header/d file.txt
Re: Seek and delete
by johngg (Canon) on May 22, 2008 at 21:36 UTC
    You could use the flip-flop operator (..).

    $ cat lines line 1 line 2 line 3 line 4 line 5 line 6 $ perl -ne 'print if $. == 3 .. eof;' lines line 3 line 4 line 5 line 6 $ perl -ne 'print if /5/ .. eof;' lines line 5 line 6 $

    I hope this is useful.

    Cheers,

    JohnGG