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)
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)
Use grep with -C option, easiest solution:
grep -C 10 'what_to_search' file.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With