almas almas - 1 year ago 75
Bash Question

Numbering lines matching the pattern using sed

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?

Answer Source

You can use grep:

grep -n pattern file

If you use = in sed 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.

sed -n '/pattern/{=;p}' file | sed '{N;s/\n/ /}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download