paulo@0: #!/usr/bin/env python paulo@0: paulo@17: # rcg.py -- regex colored grep paulo@17: # Copyright (C) 2010 by Paulo Ang (pbba13@gmail.com) paulo@17: # paulo@17: # This program is free software: you can redistribute it and/or modify paulo@17: # it under the terms of the GNU General Public License as published by paulo@17: # the Free Software Foundation, either version 3 of the License, or paulo@17: # (at your option) any later version. paulo@17: # paulo@17: # This program is distributed in the hope that it will be useful, paulo@17: # but WITHOUT ANY WARRANTY; without even the implied warranty of paulo@17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the paulo@17: # GNU General Public License for more details. paulo@17: # paulo@17: # You should have received a copy of the GNU General Public License paulo@17: # along with this program. If not, see . paulo@17: paulo@17: paulo@0: import sys paulo@0: import re paulo@0: import getopt paulo@0: paulo@0: #x = "\x1B[1;31;49m" + x paulo@0: #x = START + c["white"][0] + ";" + c["blue"][1] + END + x + CLEAR paulo@0: paulo@0: START = "\x1B[" paulo@0: BOLD = "1;" paulo@0: END = "m" paulo@0: CLEAR = START + "0" + END paulo@0: paulo@0: c = { paulo@0: # color : (fg, bg) paulo@0: "black" : ("30", "40"), paulo@0: "red" : ("31", "41"), paulo@0: "green" : ("32", "42"), paulo@0: "brown" : ("33", "43"), paulo@0: "blue" : ("34", "44"), paulo@0: "magenta" : ("35", "45"), paulo@0: "cyan" : ("36", "46"), paulo@0: "white" : ("37", "47"), paulo@0: "default" : ("39", "49"), paulo@0: } paulo@0: paulo@0: bold = False paulo@0: fg = None paulo@0: bg = None paulo@11: colorLine = False paulo@0: paulo@11: (optvals, args) = getopt.getopt(sys.argv[1:], "f:b:Bl") paulo@0: paulo@0: for (opt, val) in optvals: paulo@0: if opt == '-B': paulo@0: bold = True paulo@0: elif opt == '-f': paulo@0: fg = val paulo@0: elif opt == '-b': paulo@0: bg = val paulo@11: elif opt == '-l': paulo@11: colorLine = True paulo@0: paulo@0: if len(args) > 0: paulo@0: for line in sys.stdin: paulo@0: repl = START paulo@0: if bold: paulo@0: repl += BOLD paulo@0: if fg is not None: paulo@0: repl += c[fg][0] paulo@0: if bg is not None: paulo@0: repl += ';' + c[bg][1] paulo@0: repl += END + r'\1' + CLEAR paulo@11: paulo@11: x = line paulo@11: paulo@11: if colorLine == False: paulo@11: x = re.sub(r'(' + args[0] + r')', repl, line) paulo@11: else: paulo@11: if re.search(args[0], line) != None: paulo@11: last_char = line[-1] paulo@11: x = repl.replace(r'\1', line[:-1]) paulo@11: x += last_char paulo@0: paulo@0: sys.stdout.write(x) paulo@0: sys.stdout.flush()