I have multiple lines where i need to select only those lines which contains a specific value. For instance,
[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
so i have a variable as var=1984.
id=re.search(r'\[var\],s,re.I|re.M|re.S)
if id:
print line
THe above regex is expected to search only the var=1984 and should print lines containing that value "[1984]".Could anyone suggest how to do this?I need this to search in Linux and i am using Python 2.6.
this regex should work:
var=1984
reg = '.+'+str(var)+'.+'
id=re.search(reg,s,re.I|re.M|re.S)
or for simple:
import re
s = ['[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
for line in s:
id = re.findall(r'.+%d.+' % var, line, re.I | re.M | re.S)
if id:
print line
output:
[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized
You can also do it with a simple if
condition:
from io import StringIO
text = StringIO(u"""\
[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
""")
for line in text:
if '[1984]' in line:
print line
[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized
This should work:
#!/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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.