我想从文件中提取一些行并输出每个提取行前面的行号.
例如,在名为的文件中使用以下输入 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
如何插入行号?
保持行号的变量是$.
,所以在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)