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

Dear Monks, I was wondering, is there a way of grepping the 2nd line from a file without going the "normal" way, i.e. open FILE, $file etc? I am just asking for a quick one, I know how to do it by opening the file and either using a while loop or storing all lines in an array.

Replies are listed 'Best First'.
Re: Grep the second line from a file? (flip a coin)
by toolic (Bishop) on Mar 19, 2014 at 23:58 UTC
    Non-Perl solution on unix to get just the 2nd line of a file:
    head -2 file | tail -1
Re: Grep the second line from a file?
by Anonymous Monk on Mar 19, 2014 at 23:42 UTC

    Not sure what exactly you mean by "grepping the 2nd line from a file", could you provide some sample input with expected output?

    # prints only the second line of the file perl -ne 'print if $.==2' -- FILENAME # prints only the second line of the file if it matches a pattern perl -ne 'print if $.==2 && /pattern/' -- FILENAME
      Depending on how large the input file(s) might be, it could be worthwhile to type just two more little words:
      perl -ne 'print and last if $.==2' -- FILENAME
      Many thanks, your first snippet of code is all I need :)