Bash Scripting – How to Colorize Second Column of Output

colorstext processing

let's say, I have following output from ls:

$ ls -lAhF /bin
-rwxr-xr-x 1 root root 905K Apr 10  2010 bash*
-rwxr-xr-x 3 root root  31K Dec 26  2011 bunzip2*
-rwxr-xr-x 1 root root 505K Nov 15  2010 busybox*
-rwxr-xr-x 3 root root  31K Dec 26  2011 bzcat*
lrwxrwxrwx 1 root root    6 Jun 24  2012 bzcmp -> bzdiff*
...

I am looking for a way, how I could colorize the second column. I know how to use sed to colorize any pattern, but I don't know how to colorize specific column. Basically, I need to insert '\033[0;31m' after the first space and '\033[0m' infront of the the second space. Or perhaps there is much more elegant way ?

Best Answer

With GNU grep provided it has been build with PCRE support:

ls -l | GREP_COLORS='mt=1;41;37' grep --color -P '^\S+\s+\K\S+'

With sed:

on=$(tput setaf 7; tput setab 1; tput bold) off=$(tput sgr0)
ls -l | sed "s/[^[:blank:]]\{1,\}/$on&$off/2"

Note that using setaf assumes the terminal supports ANSI colour escape sequences, so you might as well hard code it, which would make it less verbose as well. Here with ksh93 (also bash and zsh) syntax:

on=$'\e[1;47;37m' off=$'\e[m'

To generalise to the nth column:

n=5

GREP_COLORS='mt=1;41;37' grep --color -P "^(\S+\s+){$(($n-1))}\K\S+"

sed "s/[^[:blank:]]\{1,\}/$on&$off/$n"

References