Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line number of a file in Perl

Tags:

perl

In awk if I give more than one file as an argument to awk, there are two special variables:

NR=line number corresponding to all the lines in all the files.

FNR=line number of the current file.

I know that in Perl, $. corresponds to NR (current line among lines in all of the files).

Is there anything comparable to FNR of AWK in Perl too?

Let's say I have some command line:

perl -pe 'print filename,<something special which hold the current file's line number>'  *.txt

This should give me output like:

file1.txt 1
file1.txt 2
file2.txt 1
like image 972
Vijay Avatar asked Sep 12 '12 09:09

Vijay


2 Answers

There is no such variable in Perl. But you should study eof to be able to write something like

perl -ne 'print join ":", $. + $sum, $., "\n"; $sum += $., $.=0  if eof;' *txt
like image 34
choroba Avatar answered Sep 21 '22 00:09

choroba


Actually, the eof documentation shows a way to do this:

# reset line numbering on each input file
while (<>) {
    next if /^\s*#/;  # skip comments
    print "$.\t$_";
} continue {
    close ARGV if eof;  # Not eof()!
}

An example one-liner that prints the first line of all files:

$ perl -ne 'print "$ARGV : $_" if $. == 1; } continue { close ARGV if eof;' *txt
like image 145
Zaid Avatar answered Sep 23 '22 00:09

Zaid