Created
December 31, 2017 09:49
-
-
Save zed/816ea46bbd5bf17cec730bc951bb38dc to your computer and use it in GitHub Desktop.
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/env python | |
| """Emulate: grep -Ff <letters> [<words>]""" | |
| import curses | |
| import os | |
| import sys | |
| import re | |
| if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): | |
| curses.setupterm() | |
| d = lambda b, encoding=sys.stdout.encoding: b.decode(encoding) | |
| BOLD = d(curses.tigetstr('bold')) | |
| RED = d(curses.tparm(curses.tigetstr("setaf"), curses.COLOR_RED)) | |
| RESET = d(curses.tigetstr('sgr0')) | |
| else: # output is not to a terminal | |
| BOLD = RED = RESET = '' | |
| with open(sys.argv[1]) as file: | |
| parts = file.read().splitlines() | |
| # find parts, longest first | |
| pattern = re.compile('({})'.format( | |
| '|'.join(map(re.escape, sorted(parts, key=len, reverse=True))))) | |
| def highlighted(pattern, line): | |
| return pattern.sub(r'{BOLD}{RED}\1{RESET}'.format(**globals()), line) | |
| # highlight found parts | |
| for line in sys.stdin: | |
| if pattern.search(line): # found pattern in the line | |
| sys.stdout.write(highlighted(pattern, line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment