http://www.perlmonks.org?node_id=490110

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

Dear Monks,
I need to delete the first line of a file, i.e, if a file's content were:

JohnGalt DagnyTagart HenryHankRearden
After editing it should become:

DagnyTagart HenryHankRearden
I have tried the following command but it seems to delete all lines even though I did not put g(global) option:

perl -p -i -e "s/[^\n]*\n//" test.txt

Could any one tell me what is wrong over here and what is the correct way?

Regards
Ranjan

Replies are listed 'Best First'.
Re: deleting first line of a file using in-place editing
by davido (Cardinal) on Sep 08, 2005 at 06:37 UTC

    The -p option causes printing to occur via an assumed continue block. continue blocks execute even if you short circuit the assumed loop with next, so it becomes somewhat of a contortion skipping the first line while using the -p option. One way to do it (using the -p option) would be to read the first line in a BEGIN{} block and do nothing with it, but that's silly because there's a better solution. If you really don't want to print one (or maybe several) of the lines, retake control over print by using the -n option instead of -p.

    perl -ni.bak -e "print if $line++;"

    The preceeding snippet does an inline edit where the first line is not echoed back out to the output file again, but all subsequent lines are.


    Dave

Re: deleting first line of a file using in-place editing
by sk (Curate) on Sep 08, 2005 at 06:39 UTC
    [sk]% cat test.txt JohnGalt DagnyTagart HenryHankRearden [sk]% perl -i -ne 'print if $. > 1' test.txt [sk]% cat test.txt DagnyTagart HenryHankRearden
Re: deleting first line of a file using in-place editing
by greenFox (Vicar) on Sep 08, 2005 at 06:41 UTC

    In the spirit of TIMTOWTDI...

    perl -ni -e "print unless $. == 1" test.txt

    --
    Murray Barton
    Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho

Re: deleting first line of a file using in-place editing
by monkfan (Curate) on Sep 08, 2005 at 06:37 UTC
    I learned this from merlyn.
    perl -n -e 'print unless 1..1' your_file > outputfile

    Regards,
    Edward
Re: deleting first line of a file using in-place editing
by ranjan_jajodia (Monk) on Sep 08, 2005 at 06:44 UTC
    Thanks Monks! The answers given by you work :-).

    Regards,
    Ranjan