Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbering lines matching the pattern using sed

Tags:

shell

unix

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?

like image 357
almas Avatar asked May 14 '12 03:05

almas


People also ask

How can sed be used to identify a pattern?

1. Basic text substitution using 'sed' Any particular part of a text can be searched and replaced by using searching and replacing pattern by using `sed` command. In the following example, 's' indicates the search and replace task.

How do you find the line number on a UNIX pattern?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.

How do you insert a sed line after a pattern?

The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.


3 Answers

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.

GNU sed:

sed -n '/pattern/{=;p}' file | sed '{N;s/\n/ /}'

MacOS sed:

sed -n -e '/pattern/{=' -e 'p' -e '}' file | sed -e '{N' -e 's/\n/ /' -e '}'
like image 187
Dennis Williamson Avatar answered Oct 21 '22 01:10

Dennis Williamson


= is used to print the line number.

sed -n /PATTERN/{=;p;}
like image 30
Prince John Wesley Avatar answered Oct 21 '22 00:10

Prince John Wesley


For sed, use following to get line number

sed -n /PATTERN/= 
like image 11
Arjun P R Avatar answered Oct 21 '22 00:10

Arjun P R