view rcg.py @ 17:e618a3ff2027

add GPL notices to rcg.c and rcg.py
author paulo@thepaulopc
date Mon, 13 Dec 2010 23:41:41 -0800
parents 6627edb46f36
children
line source
1 #!/usr/bin/env python
3 # rcg.py -- regex colored grep
4 # Copyright (C) 2010 by Paulo Ang (pbba13@gmail.com)
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 import sys
21 import re
22 import getopt
24 #x = "\x1B[1;31;49m" + x
25 #x = START + c["white"][0] + ";" + c["blue"][1] + END + x + CLEAR
27 START = "\x1B["
28 BOLD = "1;"
29 END = "m"
30 CLEAR = START + "0" + END
32 c = {
33 # color : (fg, bg)
34 "black" : ("30", "40"),
35 "red" : ("31", "41"),
36 "green" : ("32", "42"),
37 "brown" : ("33", "43"),
38 "blue" : ("34", "44"),
39 "magenta" : ("35", "45"),
40 "cyan" : ("36", "46"),
41 "white" : ("37", "47"),
42 "default" : ("39", "49"),
43 }
45 bold = False
46 fg = None
47 bg = None
48 colorLine = False
50 (optvals, args) = getopt.getopt(sys.argv[1:], "f:b:Bl")
52 for (opt, val) in optvals:
53 if opt == '-B':
54 bold = True
55 elif opt == '-f':
56 fg = val
57 elif opt == '-b':
58 bg = val
59 elif opt == '-l':
60 colorLine = True
62 if len(args) > 0:
63 for line in sys.stdin:
64 repl = START
65 if bold:
66 repl += BOLD
67 if fg is not None:
68 repl += c[fg][0]
69 if bg is not None:
70 repl += ';' + c[bg][1]
71 repl += END + r'\1' + CLEAR
73 x = line
75 if colorLine == False:
76 x = re.sub(r'(' + args[0] + r')', repl, line)
77 else:
78 if re.search(args[0], line) != None:
79 last_char = line[-1]
80 x = repl.replace(r'\1', line[:-1])
81 x += last_char
83 sys.stdout.write(x)
84 sys.stdout.flush()