Pattern Search between specific lines and print line numbers

grepsed

I have a file of 20 lines. I want to search for a string between the lines 10 and 15 and print the string along with the line numbers of the original file.

I have tried sed -n 10,15p file | grep -n "pattern"

The problem with the above command is, the output line number 10 of sed will be line number 1 for grep.

Hence it is not printing the line numbers from the original file.

Best Answer

When working w/ sed I typically find it easiest to consistently narrow my possible outcome. This is why I sometimes lean on the !negation operator. It is very often more simple to prune uninteresting input away than it is to pointedly select the interesting kind - at least, this is my opinion on the matter.

I find this method more inline with sed's default behavior - which is to auto-print pattern-space at script's end. For simple things such as this it can also more easily result in a robust script - a script that does not depend on certain implementations' syntax extensions in order to operate (as is commonly seen with sed {functions}).

This is why I recommended you do:

sed '10,15!d;/pattern/!d;=' <input

...which first prunes any line not within the range of lines 10 & 15, and from among those that remain prunes any line which does not match pattern. If you find you'd rather have the line number sed prints on the same line as its matched line, I would probably look to paste in that case. Maybe...

sed '10,15!d;/pattern/!d;=' <input |
paste -sd:\\n -

...which will just alternate replacing input \newlines with either a : character or another \newline.

For example:

seq 150 |
sed '10,50!d;/5/!d;=' |
paste -sd:\\n -

...prints...

15:15
25:25
35:35
45:45
50:50
Related Question