tags:

views:

71

answers:

2

I am trying to have the command run to extract a range of dates from a file and print them

ex: sed -ne '/^2009-08-20/,/^2009-08-26/p'

Yet I have multiple occurances of 2009-08-26 in the file, I want all of them to return, yet it only returns the first one. Is it possible to have ALL return?

Thanks!

+4  A: 

sed -ne '/^2009-08-20/,/^2009-08-26/b e;/^2009-08-26/b e;d;:e p'

To explain: 'e' is a label and if you are in the range you branch to that label. You give a second chance and you check if it is the end of the range. If not, delete the line.

Vereb
Awesome!!!!! thank you so much!
hey, I like that solution. You can make it even shorter by omitting th explicit label and the print by using autoprint: `sed -e '/^2009-08-20/,/^2009-08-26/b;/^2009-08-26/b;d'`
mihi
You are right! This looks better.
Vereb
+2  A: 

The reason why it returns only the first match of the end date is that a range ranges from the first match of the first pattern to the first match of the second pattern (inclusive) and will then stop printing until the first pattern occurs again. If you don't have problem writing the second pattern three times, you can use

sed -ne '/^2009-08-20/,/^2009-08-26/{/^2009-08-26/!p};/^2009-08-26/p'

which will print a line if it is between start date (inclusive) and end date (exclusive) - that's what the ! does) or if it starts with the end date.

mihi