python实现搜过关键词下上文
python实现搜过关键词上下文
就是grep -B 的功能。要搜索的关键词储存在一个变量中。在文件中查找这个关键词的上面两行的内容,并存储在一个变量中,
不知道怎么实现。想过调用系统命令grep,不知道怎么把变量的直传递给grep。。。。
谢谢大家了。
------解决方案--------------------
就是grep -B 的功能。要搜索的关键词储存在一个变量中。在文件中查找这个关键词的上面两行的内容,并存储在一个变量中,
不知道怎么实现。想过调用系统命令grep,不知道怎么把变量的直传递给grep。。。。
谢谢大家了。
------解决方案--------------------
- Python code
#!/usr/bin/env python import re class GrepLines(object): def __init__(self, max): self._max = max self._array = [] def push(self, line): if len(self._array) >= self._max: self._array.pop(0) self._array.append(line) def __str__(self): return ''.join(self._array) def Grep(file, key, count): gl = GrepLines(count) with open(file, 'r') as fd: for line in fd: rs = re.search(key, line) if rs: print gl else: gl.push(line) fd.close() if __name__ == '__main__': Grep('test2.txt', r'3.3.31.3', 3)
------解决方案--------------------
~/ cat /tmp/test.txt
line 00
line 01
line 02
line 03
line 04
line 05
line 06
line 07
line 08
line 09
line 10
~/ grep -B 2 "line 1" /tmp/test.txt
line 08
line 09
line 10
- Python code
In [1]: import subprocess In [2]: result = subprocess.check_output(['grep', '-B', '2', 'line 1', '/tmp/test.txt']) In [3]: result Out[3]: 'line 08\nline 09\nline 10\n'
------解决方案--------------------
[Quote=引用:]
- Python code
In [2]: result = subprocess.check_output(['grep', '-B', '2', 'line 1', '/tmp/test.txt'])
------解决方案--------------------
排版烂了,反正就是这句
grep -B2 $ins $file