Perl 中文件的行号 [英] Line number of a file in Perl

查看:62
本文介绍了Perl 中文件的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

awk 中,如果我给多个文件作为 awk 的参数,有两个特殊变量:

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

NR=所有文件中所有行对应的行号.

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

FNR=当前文件的行号.

我知道在 Perl 中,$. 对应于 NR(所有文件中的当前行).

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

在 Perl 中还有什么可以与 AWK 的 FNR 相媲美的吗?

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

假设我有一些命令行:

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

推荐答案

Perl 中没有这样的变量.但是你应该学习 eof 才能写出类似的东西

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

这篇关于Perl 中文件的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆