我想从文件中提取一些行,并在每个提取行的前面输出行号。
例如,在名为file
This is line1 This is line2 This is test1 This is test2 This is linex
执行perl命令后
perl -ne 'if (/test/) {print "$_"}' file
我得到了这个:
This is test1 This is test2
但我想在行的开头插入行号。
line3: This is test1 line4: This is test2
如何插入行号?
答案 0 :(得分:9)
保持行号的变量为$.
,因此请在print
函数的双引号中使用它进行插值:
perl -ne 'if (/test/) {print "line$.: $_"}' file
它产生:
line3: This is test1
line4: This is test2
答案 1 :(得分:6)
实际上我认为使用grep更容易:
grep -n test file