1 | n/a | #! /usr/bin/env python3 |
---|
2 | n/a | |
---|
3 | n/a | """Reverse grep. |
---|
4 | n/a | |
---|
5 | n/a | Usage: rgrep [-i] pattern file |
---|
6 | n/a | """ |
---|
7 | n/a | |
---|
8 | n/a | import sys |
---|
9 | n/a | import re |
---|
10 | n/a | import getopt |
---|
11 | n/a | |
---|
12 | n/a | |
---|
13 | n/a | def main(): |
---|
14 | n/a | bufsize = 64 * 1024 |
---|
15 | n/a | reflags = 0 |
---|
16 | n/a | opts, args = getopt.getopt(sys.argv[1:], "i") |
---|
17 | n/a | for o, a in opts: |
---|
18 | n/a | if o == '-i': |
---|
19 | n/a | reflags = reflags | re.IGNORECASE |
---|
20 | n/a | if len(args) < 2: |
---|
21 | n/a | usage("not enough arguments") |
---|
22 | n/a | if len(args) > 2: |
---|
23 | n/a | usage("exactly one file argument required") |
---|
24 | n/a | pattern, filename = args |
---|
25 | n/a | try: |
---|
26 | n/a | prog = re.compile(pattern, reflags) |
---|
27 | n/a | except re.error as msg: |
---|
28 | n/a | usage("error in regular expression: %s" % msg) |
---|
29 | n/a | try: |
---|
30 | n/a | f = open(filename) |
---|
31 | n/a | except IOError as msg: |
---|
32 | n/a | usage("can't open %r: %s" % (filename, msg), 1) |
---|
33 | n/a | f.seek(0, 2) |
---|
34 | n/a | pos = f.tell() |
---|
35 | n/a | leftover = None |
---|
36 | n/a | while pos > 0: |
---|
37 | n/a | size = min(pos, bufsize) |
---|
38 | n/a | pos = pos - size |
---|
39 | n/a | f.seek(pos) |
---|
40 | n/a | buffer = f.read(size) |
---|
41 | n/a | lines = buffer.split("\n") |
---|
42 | n/a | del buffer |
---|
43 | n/a | if leftover is None: |
---|
44 | n/a | if not lines[-1]: |
---|
45 | n/a | del lines[-1] |
---|
46 | n/a | else: |
---|
47 | n/a | lines[-1] = lines[-1] + leftover |
---|
48 | n/a | if pos > 0: |
---|
49 | n/a | leftover = lines[0] |
---|
50 | n/a | del lines[0] |
---|
51 | n/a | else: |
---|
52 | n/a | leftover = None |
---|
53 | n/a | for line in reversed(lines): |
---|
54 | n/a | if prog.search(line): |
---|
55 | n/a | print(line) |
---|
56 | n/a | |
---|
57 | n/a | |
---|
58 | n/a | def usage(msg, code=2): |
---|
59 | n/a | sys.stdout = sys.stderr |
---|
60 | n/a | print(msg) |
---|
61 | n/a | print(__doc__) |
---|
62 | n/a | sys.exit(code) |
---|
63 | n/a | |
---|
64 | n/a | |
---|
65 | n/a | if __name__ == '__main__': |
---|
66 | n/a | main() |
---|