Flash Notes

Strings - Colorize strings matching regular expressions


• How to colorize strings from a file or a stream according to specified regular expressions ?

Solution

Use the hl command.
hl sources files are available on github : git clone http://github.com/mbornet-hl/hl

• How to colorize in green the IP addresses of the /etc/hosts file ?

Solution

hl -e -g '(\<([0-9]{1,3}\.){3}[0-9]{1,3}\>)' < /etc/hosts

Result

...
...
192.168.122.2		vm-debian-6-0-0-amd64
192.168.122.3		vm-debian-6-0-1-amd64
192.168.122.4		vm-debian-6-0-2-1-amd64
192.168.122.5		vm-debian-6-0-3-amd64
192.168.122.6		vm-debian-6-0-4-amd64
192.168.122.7		vm-debian-6-0-5-amd64
192.168.122.8		vm-debian-6-0-6-amd64
...

• How to colorize the output of the "df" command ?

Solution

Use the configurations of the hl command :
df -h | hl --df

Result

Filesystem                                              Size  Used Avail Use% Mounted on
rootfs                                                  323M  215M   92M  71% /
udev                                                     10M     0   10M   0% /dev
tmpfs                                                   1.6G  2.6M  1.6G   1% /run
/dev/disk/by-uuid/71a1683e-9bdb-49c9-ae60-ab904753e6cf  323M  215M   92M  71% /
tmpfs                                                   5.0M     0  5.0M   0% /run/lock
tmpfs                                                   9.6G  1.1M  9.6G   1% /run/shm
/dev/sdc9                                               416G  356G   40G  91% /home
/dev/sdc8                                               368M   41M  309M  12% /tmp
/dev/sdc5                                               8.3G  5.8G  2.1G  74% /usr
/dev/sdc6                                               2.8G  1.4G  1.3G  54% /var
/dev/sda1                                               1.8T  1.4T  398G  78% /DATA3
/dev/sdd1                                               1.8T  1.5T  271G  85% /DATA4
/dev/sdb1                                               1.8T  1.1T  716G  59% /DATA5
/dev/loop0                                              4.4G  4.4G     0 100% /mnt/DVD

• How to colorize each color name in its own color ?

Solution

echo 'red green yellow blue magenta cyan white' | hl -r 'red' -g 'green' -y 'yellow' -b 'blue' -m 'magenta' -c 'cyan' -w 'white'

Result

red green yellow blue magenta cyan white