Created
August 26, 2011 20:42
-
-
Save pandemicsyn/1174389 to your computer and use it in GitHub Desktop.
redbo's rfind
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
python rfind.py [search term] [filename] | |
""" | |
import mmap | |
import os | |
import sys | |
_cmd, search_term, filename = sys.argv | |
with open(filename, 'r+') as fp: | |
mmapped = mmap.mmap(fp.fileno(), os.path.getsize(filename)) | |
position = mmapped.rfind(search_term) | |
if position == -1: | |
sys.exit(1) | |
else: | |
line_start = mmapped.rfind('\n', 0, position) | |
if line_start == -1: | |
line_start = 0 | |
else: | |
line_start += 1 | |
line_end = mmapped.find('\n', position) | |
if line_end == -1: | |
line_end = os.path.getsize(filename) | |
fp.seek(line_start) | |
print fp.read(line_end - line_start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment