我想从文件中提取一些行,并在每个提取的行的前面输出行号。
例如,在名为file
的文件中输入以下内容
This is line1 This is line2 This is test1 This is test2 This is linex
After I execute the perl command
perl -ne 'if (/test/) {print "$_"}' file
我得到这个:
这是test1
这是test2
但是我想在行首插入行号。
第3行:这是test1
第4行:这是test2
如何插入行号?
最佳答案
保留行号的变量是$.
,因此可以在print
函数的双引号中插入它:
perl -ne 'if (/test/) {print "line$.: $_"}' file
它产生:
line3: This is test1
line4: This is test2