Last active
November 30, 2021 12:56
-
-
Save miku/4387573 to your computer and use it in GitHub Desktop.
Simple recursive grep in python with highlighting.
This file contains 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 | |
# see: http://i.imgur.com/X7JCr.png | |
import re | |
import os | |
import argparse | |
TEXTCHARS = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100))) | |
is_binary_string = lambda bytes: bool(bytes.translate(None, TEXTCHARS)) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser('pygrep') | |
parser.add_argument('-d', '--directory', type=str, required=False, | |
default='.', help='root directory to search') | |
parser.add_argument('pattern', type=str, help='search pattern') | |
args = parser.parse_args() | |
pattern = re.compile(args.pattern) | |
for path, _, files in os.walk(args.directory): | |
for fn in files: | |
filepath = os.path.join(path, fn) | |
if is_binary_string(open(filepath).read(1024)): | |
continue | |
with open(filepath) as handle: | |
for lineno, line in enumerate(handle): | |
mo = pattern.search(line) | |
if mo: | |
print("%s:%s: %s" % (filepath, lineno, | |
line.strip().replace(mo.group(), "\033[92m%s\033[0m"% | |
mo.group()))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment