Jack Nicholson Jack Nicholson - 1 year ago 104
Linux Question

tail & grep file and uniquely color by IP addresses

I'm stuck on trying to colorize

tail -f
output so that the IP address color is unique per IP address. I can't find anything by searching.

Here's some code that colors the current IP address alone but it's the same color for every IP.

tail -f /var/www/domain.com/logs/global.log | egrep --color=auto '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'

I'm looking to have a unique color per IP address. So you can differentiate between users.

I've tried:

tail -f /var/www/domain.com/logs/global.log | GREP_COLOR='01;36' egrep --color -E '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}|$'

I'm trying to work out a way of defining the color based on what the IP is but i'm unsure on how to proceed.

But not much has helped so far. Am I on the right lines? Cheers

Answer Source

Here's a possibility in perl: tail -f YOURFILE| perl -pe 's/\d{1,3}\.\d{1,3}.(\d{1,3})\.\d{1,3}/\033[38;5;\1\2\3m$&\033[39m/g'

It replaces each IP-address looking substring with an ANSI color sequence based on its third octet.

It works the same in re2g: tail -f YOURFILE| re2g -gp '\d{1,3}\.\d{1,3}.(\d{1,3})\.\d{1,3}' -s $'\033[38;5;\\1\\2\\3m\\0\033[39m'

In perl, you can get a little fancier with your color choices though: tail -f YOURFILE| perl -pe 's/(\d{1,3})\.(\d{1,3}).(\d{1,3})\.(\d{1,3})/"\033[38;5;".(16+($1+$2+$3+$4)%214)."m$&\033[39m"/ge'. This version guarantees that the color falls into nice visible range and also bases the color on all four octets.

See also: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download