Search code examples
linuxbashgrepgnutail

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


Results

Thanks to the help below here's a working compiled answer

# Color ip address only
tail -f /var/www/file | perl -pe 's/\d{1,3}\.\d{1,3}.(\d{1,3})\.\d{1,3}/\033[38;5;\1\2\3m$&\033[39m/g'

My new most used

# Color entire line
tail -f /var/file.log | perl -pe 's/^.*(\d{1,3})\.(\d{1,3}).(\d{1,3})\.(\d{1,3}).*$/\033[38;5;\2\2\3m$&\033[39m/g'

Solution

  • 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