I'm writing the script that searches for lines that match some pattern. I must use sed for this script. This works fine for searching and printing matched lines:
sed -n /PATTERN/p
However, I'd also like to print the matched lines number in front of the line itself. How can I do that using sed?
You can use
grep
:If you use
=
insed
the line number will be printed on a separate line and is not available in the pattern space for manipulation. However, you can pipe the output into another instance of sed to merge the line number and the line it applies to.Here's the simplest way:
Switch to awk.
...
Using Perl:
$.
contain line number. If input file contains:This one-liner:
perl -ne 'print "$.: $_" if /record/' input.file
will print:Or if you just want total number of lines matched a pattern use:
perl -lne '$count++ if /regex/; END { print int $count }' input.file
=
is used to print the line number.For sed, use following to get line number