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 \n
ewlines with either a :
character or another \n
ewline.
For example:
seq 150 |
sed '10,50!d;/5/!d;=' |
paste -sd:\\n -
...prints...
15:15
25:25
35:35
45:45
50:50
sed '10,15!d;/pattern/!d;='
– mikeserv Jan 11 '15 at 04:35