Question

My question is similar to this one: Syntax highlighting/colorizing cat . But not exactly the same.

A tool, doing this would be great:

  • cat a file
  • highlight word x in color cx
  • highlight word y in color cy

etc. Does anyone know something like this?


The "real-world motivation" for this is: I have a log (generated by log4cxx for example) and I want to highlight DEBUG in one color; ERROR in another; WARN in third, etc.

Basically, what I'm trying to achieve is: How to set colour of console output of log4cxx?

I think about some kind of combination between cat and grep (with custom colors). But an external tool would do the job, too (if exists).

Ideas?


EDIT: Thanks, @sjngm! Great suggestion. I modified it a bit (now can be used as alias and also the whole rows are highlighted). I decided to post my modifications, as this could be useful for somebody:

 # escaped ' ------------v;         light red ------vvvv;  red ------------vvvv;  yellow -------vvvvv;  green ---------vvvv;  brown ----------vvvv;  dark gray ------vvvv
 alias log_color='nawk '"'"'BEGIN { arr["FATAL"] = "1;31"; arr["ERROR"] = "0;31"; arr["WARN"] = "1;33"; arr["INFO"] = "0;32"; arr["DEBUG"] = "0;33"; arr["TRACE"] = "1;30"  } { l = $0; for (pattern in arr)     { gsub(".*" pattern ".*", "\033[" arr[pattern] "m&\033[0m", l); } print l; }'"'"
 alias log_error='grep "FATAL\|ERROR\|WARN"'

Example usage:

$ cat log_file | log_color
$ cat log_file | log_error | log_color
Was it helpful?

Solution

A while ago I did something similar, also for a log-file, with nawk:

cat yourfile | nawk '
BEGIN {
    arr["EXCEPTION"] = "0;31";
    arr["\\[ERROR\\]"] = "1;31";
    arr["\\[WARN\\]"] = "0;31";
    arr["\\[INFO\\]"] = "1;34";
}
{
    l = $0;
    for (pattern in arr) {
        gsub(pattern, "\033[" arr[pattern] "m&\033[0m", l);
    }
    print l;
}'

The configuration part should match your x => cx style, you could also use tail -f instead of cat.

To be honest I don't think there's a tool for it as it's not that complex.

OTHER TIPS

Here you will find a sed-wrapper that will simply accept colors and patterns as a command line arguments:

https://stackoverflow.com/a/13593327/1033410

(usage: cat yourfile | colorize.sh red ERROR yellow WARN blue 'user .* logged in')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top