How do I print the line number with each matched line?
perl, regex
Solution
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
Problem
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?