我有多行,我只需要选择那些包含特定值的行。例如,
[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized
[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Logger Initialized
[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Actuation Logger Initialized
所以我有一个变量为var = 1984。
id=re.search(r'\[var\],s,re.I|re.M|re.S)
if id:
print line
上面的正则表达式预期仅搜索var = 1984,并且应该打印包含该值“ [1984]”的行。有人可以建议如何执行此操作吗?我需要在Linux中进行搜索并且我正在使用Python 2.6。
这应该工作:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
var = '\[1984\]'
with open("test.log") as fp: # assuming your log file is test.log
lines = fp.readlines()
for line in lines:
line = line.strip()
if re.match(r'.*'+str(var)+'.*',line): # may be you want to add some more strict matching rules here.
print line
# vim:ai:et:sts=4:sw=4:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句