Thursday, July 28, 2011

Using sed and awk to highlight console output.

Using ANSI escape sequences in ASCII code I can use awk to highlight lines.

This is really useful for scanning output from make or reading logs.

$ cat TestInput
sdfasd
This is a test abcd test abcd
asdfsd test sdfasdfas

sdfasdffetestasdfasdfas

sdfs
daf
sdf

$ cat highlight
awk '/test/ {print "\033[30;47m" $0 "\033[37;40m"}' TestInput
$ ./highlight

This is a test abcd test abcd
asdfsd test sdfasdfas
sdfasdffetestasdfasdfas
$

I can change the colors.

$ cat highlight
awk '/test/ {print "\033[32;41m" $0 "\033[37;40m"}' TestInput
$ ./highlight

This is a test abcd test abcd
asdfsd test sdfasdfas
sdfasdffetestasdfasdfas

$

Here is a list of color codes.

Terminal Color changing come in the form of  esc , ASCII Decimal 27, hex 1B octal 33
esc[background ; foreground m
It's important there be no spaces.
 
"\033[32;41m"
 so \033 sends escape,   32;41 is background and foreground and "m" is the command.

I can do the same trick with SED also.

 
[jsokol]$ cat highlight2
sed  's/test/\d27[32;41m\0\d27[37;40m/g' TestInput
[jsokol]$ ./highlight2
sdfasd
This is a test abce test aaxx
asdfsd test sdfasdfas 
 
sdfasdffetestasdfasdfas
 
sdfs
daf
sdf
 
[jsokol]$

No comments: