Skip to content

Instantly share code, notes, and snippets.

@miku
Last active November 30, 2021 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miku/4387573 to your computer and use it in GitHub Desktop.
Save miku/4387573 to your computer and use it in GitHub Desktop.
Simple recursive grep in python with highlighting.
#!/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