Perl: extract strings from 1 to n (Windows)

I want to extract lines 1 to n from my .csv file. Using this

perl -ne 'if ($. == 3) {print;exit}' infile.txt 

I can only extract one line. How to put a row of lines in this script?

+3
source share
3 answers

What happened with:

head -3 infile.txt

If you really have to use Perl, then this works:

perl -ne 'if ($. <= 3) {print} else {exit}' infile.txt 
+2
source

If you have only one range and one, possibly concatenated input stream, you can use:

#!/usr/bin/perl -n
if (my $seqno = 1 .. 3) {
    print;
    exit if $seqno =~ /E/;
}

But if you want it to apply to every input file, you need to catch the end of each file:

#!/usr/bin/perl -n
print if my $seqno = 1 .. 3;
close ARGV if eof || $seqno =~ /E/;

And if you want to be kind to people who forget args, add a good warning to the sentence BEGINor INIT:

#!/usr/bin/perl -n
BEGIN { warn "$0: reading from stdin\n" if @ARGV == 0 && -t }
print if my $seqno = 1 .. 3;
close ARGV if eof || $seqno =~ /E/;

:

  • -n -p #!. ( ) , ‑l ‑a.

  • readline, 1 .. 3 ($. == 1) .. ($. == 3).

  • eof parens , ARGV . eof(), <ARGV>.

  • - "E0".

  • -t, libcs ​​ isatty(3), STDIN - filetest.

  • A BEGIN{} , , script ‑MO=Deparse, , , . INIT{} .

  • , , LINE, , , , .

+11

:

perl -ne 'if (1 .. 3) { print } else { last }' infile.txt
+2

Source: https://habr.com/ru/post/1772464/


All Articles