I would like to search through a range of lines in a date ordered log file between two dates. If I were at the command line, sed
would come handy with:
sed -rn '/03.Nov.2012/,/12.Oct.2013/s/search key/search key/p' my.log
The above would only display lines between the 3 November, 2012 and 12 of October, 2013 that contain the string "search key
".
Is there a light weight way I can do this in python
?
I could build a single RE for the above , but it would be nightmarish.
The best I can come up with is this:
#!/usr/bin/python
start_date = "03/Nov/2012"
end_date = "12/Oct/2013"
start = False
try:
with open("my.log",'r') as log:
for line in log:
if start:
if end_date in line:
break
else:
if start_date in line:
start = True
else:
continue
if search_key in line:
print line
except IOError, e:
print '<p>Log file not found.'
But this strikes me as not 'pythonic'.
One can assume that search date limits will be found in the log file.
Using itertools
and a generator is one way:
from itertools import takewhile, dropwhile
with open('logfile') as fin:
start = dropwhile(lambda L: '03.Nov.2012' not in L, fin)
until = takewhile(lambda L: '12.Oct.2013' not in L, start)
query = (line for line in until if 'search string' in line)
for line in query:
pass # do something
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句