【发布时间】:2013-10-30 09:39:40
【问题描述】:
我想在两个日期之间的按日期排序的日志文件中搜索一系列行。如果我在命令行,sed 会派上用场:
sed -rn '/03.Nov.2012/,/12.Oct.2013/s/search key/search key/p' my.log
以上将仅显示 2012 年 11 月 3 日至 2013 年 10 月 12 日之间包含字符串“search key”的行。
我可以在python 中做到这一点吗?
我可以为上述构建单个 RE,但这将是噩梦。
我能想到的最好的是:
#!/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.'
但这让我觉得不是“pythonic”。
可以假设搜索日期限制会在日志文件中找到。
【问题讨论】: