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

查看:35
本文介绍了搜索一个单词,如果找到,则在模式匹配之前打印 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 获取匹配后的下 10 行.

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

UPDATE 排除带有 ip/mac 地址的行:

UPDATE To exclude lines with ip/mac address:

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

addr_pattern = re.compile(
    r'd{1,3}.d{1,3}.d{1,3}.d{1,3}|'
    r'[da-f]{2}:[da-f]{2}:[da-f]{2}:[da-f]{2}:[da-f]{2}:[da-f]{2}',
    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)

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

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