Grep for a word, and if found print 10 lines before and 10 lines after the pattern match

后端 未结 5 618
温柔的废话
温柔的废话 2021-01-01 05:32

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 P

5条回答
  •  孤独总比滥情好
    2021-01-01 06:30

    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)
    

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


    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)
    

提交回复
热议问题