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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
How about some short code like this in python to do context grepping:
Use
grep
with-C
option, easiest solution:used
collections.deque
to save up to 10 lines before match, anditertools.islice
to get next 10 lines after the match.UPDATE To exclude lines with ip/mac address:
Without importing any package, we can achieve this.
Explanation:
string_to_search
: word/pattern that you want to grepbefore
: number of lines that you want to print before the pattern matchafter
: number of lines that you want to print after the pattern matchmy_file.txt
is the file which contains the word/pattern/stringcurrent_lineno
will contain the line number which contains the patternSample File Content:
Sample Execution and Output:
The above code is equivalent to Unix `grep' command
Try this