Reputation: 55
I am using sed
to print log records within a time interval. My time format is YYYY-MM-DD HH:MM:ss,sss, for example "2014-07-22 15:33:25,758". I tried
sed -n '/2014-07-23 01:00:00,000/,/2014-07-23 02:00:00,000/ p'
But it does not work. I can find the solution for YYYY-MM-DD, but it is not for my case. Can anyone help?
Upvotes: 0
Views: 879
Reputation: 15501
For your sed command to work, those exact times must appear in the file. konsolebox has a good solution that should work in your case (but see Jonathan Leffler's comment there, and also his awk solution which is simpler than mine).
In general you need something more powerful than sed, like awk. In the example below, note how you must specify the input times (space-separated values, no decimals on seconds). Also note that it is gawk-specific. Also note that I've assumed the time is the first and second space-separated fields. Adjust as needed.
gawk -vstart="2014 07 23 01 00 00" -vend="2014 07 23 02 00 00" '
BEGIN {nstart=mktime(start); nend=mktime(end)}
{
t = $1 " " $2
gsub(/[-:]/, " ", t);
nt = mktime(substr(t, 1, 19))
if (nt >= nstart && nt <= nend)
print
}
' file
Upvotes: 1
Reputation: 753970
Ultimately, sed
is not the best tool for this job; it does exact matches rather than range-based matches (within the exactness of regular expressions).
Using awk
, you can do range-based checking:
awk '$1 == "2014-07-23" && $2 >= "01:00:00" && $2 < "02:00:00" { print }'
where the { print }
is optional but explicit. One of the advantages of the ISO 8601 date and time notations is precisely that lexicographic order is the same as time order.
Upvotes: 2
Reputation: 75488
You can replace insignificant digits with .
so it would match anything within the range:
sed -n '/2014-07-23 01:..:..,.../,/2014-07-23 02:..:..,.../p'
And perhaps just remove them totally:
sed -n '/2014-07-23 01:/,/2014-07-23 02:/p'
Upvotes: 3