Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5705

Selecting lines using sed

I have a text file as below:

2015-05-08 09:02 Out.dat
2015-05-08 10:45:22.617 ERROR   EventLog
2015-05-08 10:02 Out.xml
2015-05-08 11:30 Out.html
2015-05-08 05:30 Out.ps

I am trying to select line containing 10 AM till it reached anything which is not 10 am. So I am using the below sed command:

sed -rn '/[0-9]{4}-[0-9]{2}-[0-9]{2} 10:/ , /[0-9]{4}-[0-9]{2}-[0-9]{2} [^10]:/ p' test.dat

And the output is:

2015-05-08 10:45:22.617 ERROR   EventLog
2015-05-08 10:02 Out.xml
2015-05-08 11:30 Out.html
2015-05-08 05:30 Out.ps

I don't want the last line to come. It should stop at 11:30 line (3rd line of output).

Can anyone please help me with this?

Upvotes: 0

Views: 531

Answers (3)

robert
robert

Reputation: 4867

Without testing, I think what you want to do is omit the second term:

sed -rn '/[0-9]{4}-[0-9]{2}-[0-9]{2} 10:/ p' test.dat

In your example, the second term will "include" the line that matches it also. You only want to print the lines that do match, not a range between lines.

Basically it's just a grep.

EDIT: Sorry, I just realised that what you want to do is include the next line after. Your regex is fine except for "[^10]:" which "matches any value that is not 1 or 0".

You could just put 1[^0] ..

$ sed -rn '/[0-9]{4}-[0-9]{2}-[0-9]{2} 10:/ , /[0-9]{4}-[0-9]{2}-[0-9]{2} 1[^0]:/ P' test.txt
2015-05-08 10:45:22.617 ERROR   EventLog
2015-05-08 10:02 Out.xml
2015-05-08 11:30 Out.html

Upvotes: 2

choroba
choroba

Reputation: 241768

[^10]: matches anything that's not 1 or 0, i.e. a single character, followed by :, but such line is not present in your data.

It's hard to implement negation in sed. Fortunately, you don't need it:

sed -rn '/^[0-9]{4}-[0-9]{2}-[0-9]{2} 10:/ p'

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '/^[0-9-]* 10:/ !d' YourFile
  • remove any line not having 10: after the date
  • use -i for inline editing (not streaming in this case)

Upvotes: 1

Related Questions