用grep表示一个单词,如果找到,则在模式匹配前打印10行,在模式匹配后打印10行 [英] Grep for a word, and if found print 10 lines before and 10 lines after the pattern match

查看:118
本文介绍了用grep表示一个单词,如果找到,则在模式匹配前打印10行,在模式匹配后打印10行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个巨大的文件.我想在该行中搜索一个单词,找到后我应该在模式匹配之前打印10行,在模式匹配之后打印10行.如何在Python中做到这一点?

I am processing a huge file. I want to search for a word in the line and when found I should print 10 lines before and 10 lines after the pattern match. How can I do it in Python?

推荐答案

import collections
import itertools
import sys

with open('huge-file') as f:
    before = collections.deque(maxlen=10)
    for line in f:
        if 'word' in line:
            sys.stdout.writelines(before)
            sys.stdout.write(line)
            sys.stdout.writelines(itertools.islice(f, 10))
            break
        before.append(line)

使用 collections.deque 最多保存10行匹配之前,然后 itertools.islice 即可获得下一行比赛.

used collections.deque to save up to 10 lines before match, and itertools.islice to get next 10 lines after the match.

更新要排除具有ip/mac地址的行:

UPDATE To exclude lines with ip/mac address:

import collections
import itertools
import re  # <---
import sys

addr_pattern = re.compile(
    r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|'
    r'\b[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}\b',
    flags=re.IGNORECASE
)  # <--

with open('huge-file') as f:
    before = collections.deque(maxlen=10)
    for line in f:
        if addr_pattern.search(line):  # <---
            continue                   # <---
        if 'word' in line:
            sys.stdout.writelines(before)
            sys.stdout.write(line)
            sys.stdout.writelines(itertools.islice(f, 10))
            break
        before.append(line)

这篇关于用grep表示一个单词,如果找到,则在模式匹配前打印10行,在模式匹配后打印10行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆