|
| 1 | +#! /bin/python3 |
| 2 | +# |
| 3 | +# Search for keywords in files reachable from current directory. |
| 4 | + |
| 5 | + |
| 6 | +from sys import argv |
| 7 | +from os.path import basename |
| 8 | +import readline |
| 9 | +from subprocess import run, PIPE |
| 10 | + |
| 11 | + |
| 12 | +VERBOSE = False |
| 13 | +INSENSITIVE = False |
| 14 | + |
| 15 | +def help(): |
| 16 | + print(f'Syntax: {basename(argv[0])} (-i|-v|-h)') |
| 17 | + print('\t-i:\tCase insensitive search.') |
| 18 | + print('\t-v:\tVerbose.') |
| 19 | + print('\t-h:\tHelp.') |
| 20 | + |
| 21 | +def green(text): |
| 22 | + return "\33[32m" + text + "\33[0m" |
| 23 | + |
| 24 | +def main(): |
| 25 | + # configure extension |
| 26 | + ext = input('Extensions: [c|cpp] ') |
| 27 | + |
| 28 | + if ext == '': |
| 29 | + ext = 'c|cpp' |
| 30 | + elif ext.startswith('[') and ext.endswith(']'): |
| 31 | + ext.strip('[]') |
| 32 | + elif ext.startswith('(') and ext.endswith(')'): |
| 33 | + ext.strip('()') |
| 34 | + |
| 35 | + r = run(['find', '.', '-type', 'f', '-regex', |
| 36 | + '.*/.*\\.\\(' + ext.replace('|', '\\|') + '\\)'], stdout=PIPE) |
| 37 | + r.check_returncode() |
| 38 | + |
| 39 | + if len(r.stdout) == 0: |
| 40 | + print(f"It seems that no file match extension '{ext}'") |
| 41 | + exit(1) |
| 42 | + |
| 43 | + # configure search string (format: bytes) |
| 44 | + search_str = input('Search string: ').encode('utf8') |
| 45 | + if INSENSITIVE: |
| 46 | + search_str = search_str.upper() |
| 47 | + |
| 48 | + print("Searching for '" + search_str.decode('utf8') + "' ...") |
| 49 | + |
| 50 | + for name in r.stdout.decode('utf8').strip('\n').split('\n'): |
| 51 | + name_shown = False |
| 52 | + for line in open(name, 'rb').read().split(b'\n'): |
| 53 | + if search_str in ((INSENSITIVE and line.upper()) or line): |
| 54 | + if not name_shown or VERBOSE: |
| 55 | + print(green(name)) |
| 56 | + name_shown = True |
| 57 | + run(['grep', '--color=always', search_str], input=line) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + if len(argv) > 1: |
| 62 | + for arg in argv[1:]: |
| 63 | + if arg == '-i': |
| 64 | + INSENSITIVE = True |
| 65 | + elif arg == '-v': |
| 66 | + VERBOSE = True |
| 67 | + elif arg == '-h': |
| 68 | + help() |
| 69 | + exit(0) |
| 70 | + main() |
0 commit comments