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?
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.
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.
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.
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 '}'
=
is used to print the line number.
sed -n /PATTERN/{=;p;}
For sed, use following to get line number
sed -n /PATTERN/=
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With