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

Fellow monks,

perl -ne '@A=split(","); print join(",", @A[0 .. 3]),"\n"' $TEMPDIR/rf +plan.1 | sed '1d' >> $TEMPDIR/rfplan.2


In the above script I am using a sed command to remove the first line from the output of perl script. How can I apply that logic too, inside the one line perl code ?

Replies are listed 'Best First'.
Re: Removing the First Line
by kyle (Abbot) on Jan 30, 2007 at 01:50 UTC

    I bet there's a better way, using something in perlvar, but this works:

    perl -ne 'next unless $after_first_line++;@A=split(","); print join(",", @A[0 .. 3]),"\n"'

    Update: Yeah, $. contains the line number, so:

    perl -ne 'next if ($.==1);@A=split(","); print join(",", @A[0 .. 3]),"\n"'

Re: Removing the First Line
by GrandFather (Saint) on Jan 30, 2007 at 01:57 UTC

    With quoting adapted for Windows, the following does the magic using a scalar context range operator:

    perl -ne "@A=split /,/; print join(q(,), @A[0 .. 3]),qq(\n) if 2 .. -1 +;" temp.txt

    Note that a file line number match is implied by the scalar context range operator when numeric constants are used.


    DWIM is Perl's answer to Gödel
      I don't think that -1 will work with $., better to use eof.
      perl -lne"@A=split /,/; print join(q(,), @A[0 .. 3]) if 2 .. eof" temp +.txt
Re: Removing the First Line
by jwkrahn (Abbot) on Jan 30, 2007 at 02:52 UTC
    perl -lne '$. == 1 || print join ",", (split/,/)[0 .. 3]' $TEMPDIR/rfp +lan.1 >> $TEMPDIR/rfplan.2
Re: Removing the First Line
by johngg (Canon) on Jan 30, 2007 at 09:54 UTC
    How about this to save testing every line

    perl -lne 'BEGIN{<>} print join q{,}, (split m{,})[0 .. 3];' file1 > f +ile2

    Cheers,

    JohnGG

Re: Removing the First Line
by AltBlue (Chaplain) on Jan 31, 2007 at 13:13 UTC
    On a side note, you could use perl's autosplit feature to golf this:
    perl -F, -lane 'BEGIN { <>; $, = "," } print @F[0 .. 3]' $TEMPDIR/rfpl +an.1 > $TEMPDIR/rfplan.2
Re: Removing the First Line
by rir (Vicar) on Jan 31, 2007 at 16:53 UTC
    Dropping the -n option, makes it easy to use the same logic of skipping the first line of input.

    $hdr=<>; while ( <> ){ @A=split(","); print join(",", @A[0 .. 3]),"\n" }
    Be well,
    rir