Search code examples
bashawkterminalsolaris

awk output using printf and color


I am writing a script on an old version of Solaris. Column does not exist. I want to color the second column of a string and format it into basic columns.

Currently I am using

off='\033[0m'   
gry='\033[1;90m'
line="test1 test2 test3 test4"
colored=$(echo -e "${gry}1.23${off}")
echo -e "${line}" | awk -F" " '{printf("%-10s%-10s%-10s%s\n", $1,coll,$3,$4)}' coll="${colored}"

But when run, the second colored column will have the 3rd column pressed up against it. Without the color codes the formatting is fine.

I thought this may have to do with zero length chars

off='\[\033[0m\]' 
gry='\[\033[1;90m\]'

But this just prints the extra brackets.

I want (with colored 2nd column)

test1     1.23     test3          test4
test1     1.23     test3          test4
test1     1.23     test3          test4

but getting

test1     1.23test3          test4
test1     1.23test3          test4
test1     1.23test3          test4

Solution

  • The formatting withing the printf receives your ANSI CSI codes and count them in the string parameter width regardless if they are actually printed or not.

    since you are always coloring the 2nd column, you could move the ANSI CSI sequences within the format string of the printf like this:

    line="test1 test2 test3 test4"
    colored="1.23"
    echo -e "${line}" | awk -F" " '{printf("%-10s\033[1;90m%-10s\033[1;0m%-10s%s\n", $1,coll,$3,$4)}' coll="${colored}"