如何使用每个匹配的行打印行号?

geo*_*a_e 2 regex perl

我想从文件中提取一些行并输出每个提取行前面的行号.

例如,在名为的文件中使用以下输入 file

This is line1
This is line2
This is test1
This is test2
This is linex

执行perl命令后

perl -ne 'if (/test/) {print "$_"}' file
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

This is test1
This is test2

但我想在行的开头插入行号.

line3: This is test1
line4: This is test2

如何插入行号?

Bir*_*rei 9

保持行号的变量是$.,所以在print函数的双引号中使用它进行插值:

perl -ne 'if (/test/) {print "line$.: $_"}' file
Run Code Online (Sandbox Code Playgroud)

它产生:

line3: This is test1
line4: This is test2
Run Code Online (Sandbox Code Playgroud)


Laj*_*res 6

实际上我认为使用grep更容易:

grep -n test file
Run Code Online (Sandbox Code Playgroud)