Regex 如何打印每个匹配行的行号?
我想从文件中提取一些行,并在每个提取行前面输出行号 例如,在名为Regex 如何打印每个匹配行的行号?,regex,perl,Regex,Perl,我想从文件中提取一些行,并在每个提取行前面输出行号 例如,在名为file This is line1 This is line2 This is test1 This is test2 This is linex 我得到这个: This is test1 This is test2 这是test1 这是test2 但是我想在行首插入行号 line3: This is test1 line4: This is test2 第3行:这是test1 第4行:这是test2 如何插入行号?实际上,我认为
file
This is line1
This is line2
This is test1
This is test2
This is linex
我得到这个:
This is test1
This is test2
这是test1
这是test2
但是我想在行首插入行号
line3: This is test1
line4: This is test2
第3行:这是test1
第4行:这是test2
如何插入行号?实际上,我认为使用grep更容易:
grep -n test file
保留行号的变量是
$。
,因此在print
函数的双引号中使用它:
perl -ne 'if (/test/) {print "line$.: $_"}' file
它产生:
line3: This is test1
line4: This is test2
line3: This is test1
line4: This is test2