Issue with column command and color escape codes

I’m colorizing the header of a table formatted with column -ts $'t'

Works well without color codes, but when I add color codes to the first line column doesn’t properly align the output.

Without colored output it works as expected:
printf "1t2t3nasdasdasdasdasdasdasdtqwetqweqwen" | column -ts $'t'

But when adding color on the first line column doesn’t align the text of the colored row:
printf "e[7m1t2t3e[0mnasdasdasdasdasdasdasdtqwetqweqwen" | column -ts $'t'

Observed this behaviour both on Ubuntu Linux and Mac OS X.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, that’s because the color codes are also being formatted by column. They are characters just like any other. Since you’re already using printf though, you may as well use it to do the formatting for you:

$ printf 'e[7m%-24s%-8s%-6se[0mn%-24s%-8s%-6sn' "1" "2" "3" "asdasdasdasdasdasdasd" "qwe" "qweqwe"
1                       2       3     
asdasdasdasdasdasdasd   qwe     qweqwe

Alternatively, you can add the color codes after using column:

$ printf "1t2t3nasdasdasdasdasdasdasdtqwetqweqwen" | column -ts $'t' | 
    sed "1{s/^/$(printf 'e[7m')/;s/$/$(printf 'e[0m')/}"
1                      2    3   # this line is colored
asdasdasdasdasdasdasd  qwe  qweqwe

Method 2

I imagine that column doesn’t know that e[7m is a v100 escape sequence that takes no space in the output. It seems to asssume character codes 0 to 037 octal take no space. You can get what you want by putting the initial escape sequence on a line of its own, then removing that newline from the output:

printf 'e[7mn1t2t3e[0mnasdasdasdasdasdasdasdtqwetqweqwen' | 
column -ts $'t' |
sed '1{N;s/n//}'


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x