1

I am doing a range search with sed. I want to parse the log data from the date and time 2016-09-29 01:00 to 2016-09-29 01:30. That is why I have been using the following command,

$ sed -n '/2016-09-29 01:/,/2016-09-29 01:30:.*$/p'

But problem is if 1:30 is not available in log then it returns all the logs to the end.

So how can work with this so that if 1:30 doesn't exist it will go to the just next record not till end.

Things to consider: Logs contains stack trace so lines contain stack trace doesn't start with the date.

1 Answer 1

3

Not so strange. sed is a stream editor, it processes lines as they come. A range like /a/,/b/ means the lines are selected as soon as a is found, and no-longer selected after b is found. If b is never found, it never stops selecting lines.

Here, you should rather use awk instead. Assuming those timestamps are at the beginning of the line:

awk '$0 >= "2016-09-29 01:" && $0 < "2016-09-29 01:30"'

Note that it will only select lines that have a timestamp in the range, so would excludes lines that don't have a timestamp even if they are between lines that have timestamps in the range.

Another approach to work around that would be:

awk -v start='2016-09-29 01:' -v end='2016-09-29 01:30' '
  $0 >= start && $0 <= end, /^[0-9]{4}([ :-][0-9]{2}){5}/ && $0 >= end'

That is use a range like in sed, but enter the range on the first line that is between the 2 dates, and leave it only when we find a line with a timestamp that is greater than the end date.

2
  • Worked like charm. But then I saw that it doesn't include stack traces.
    – arif
    Aug 29, 2018 at 11:22
  • @muhammad, see edit. Aug 29, 2018 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.