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 withsed
{functions}
).This is why I recommended you do:
...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 numbersed
prints on the same line as its matched line, I would probably look topaste
in that case. Maybe......which will just alternate replacing input
\n
ewlines with either a:
character or another\n
ewline.For example:
...prints...