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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With