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 "1\t2\t3\nasdasdasdasdasdasdasd\tqwe\tqweqwe\n" | column -ts $'\t'

But when adding color on the first line column doesn't align the text of the colored row:
printf "\e[7m1\t2\t3\e[0m\nasdasdasdasdasdasdasd\tqwe\tqweqwe\n" | column -ts $'\t'

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


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[7m\n1\t2\t3\e[0m\nasdasdasdasdasdasdasd\tqwe\tqweqwe\n' | 
column -ts $'\t' |
sed '1{N;s/\n//}'
  • Thanks! You're right. Also using colors in some columns of other rows where this newline workaround won't work, but I'll work around that with the method @terdon suggested. – Niklas Berglund Dec 27 '15 at 14:23

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%-6s\e[0m\n%-24s%-8s%-6s\n' "1" "2" "3" "asdasdasdasdasdasdasd" "qwe" "qweqwe"
1                       2       3     
asdasdasdasdasdasdasd   qwe     qweqwe

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

$ printf "1\t2\t3\nasdasdasdasdasdasdasd\tqwe\tqweqwe\n" | column -ts $'\t' | 
    sed "1{s/^/$(printf '\e[7m')/;s/$/$(printf '\e[0m')/}"
1                      2    3   # this line is colored
asdasdasdasdasdasdasd  qwe  qweqwe
  • Yes they're characters, but not the tab character \t which I have specified as delimiter :) Don't want to use printf to specify length, want to create columns with column – Niklas Berglund Dec 27 '15 at 10:33
  • @NiklasBerglund yes but there's no point in using the tab since your column command removes it. – terdon Dec 27 '15 at 10:34
  • @NiklasBerglund also see updated answer. You can add the colors after using column and avoid the problem. – terdon Dec 27 '15 at 10:41
  • Thanks. I want to use column because some columns are of dynamic width. Nice idea to add colors after using column 👍 – Niklas Berglund Dec 27 '15 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.