Vijay Vijay - 6 months ago 21
Perl Question

Line number of a file in 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

Answer

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
Comments