How do I print the line number with each matched line?
I want to extract some lines from a file and output the line number in front of each extracted line.
For example, with the following input in a file named 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
I obtain this:
This is test1 This is test2
But I want to insert the line number at the beginning of the line.
line3: This is test1 line4: This is test2
How can I insert the line number?
The variable that keep the line number is $.
, so use it interpolated in the double quotes of the print
function:
perl -ne 'if (/test/) {print "line$.: $_"}' file
It yields:
line3: This is test1
line4: This is test2
其实我认为使用grep更容易:
grep -n test file
链接地址: http://www.djcxy.com/p/77070.html
上一篇: 用两个替换三个回车符
下一篇: 如何在每条匹配的行上打印行号?