Shell – Tool to Tablify Input Data Containing ANSI Escape Codes

colorscolumnsshelltabulationtext processing

I have input containing ANSI color codes that I'd like to tablify. I want the output to remain colored, so the tablified output should maintain the ANSI color codes. Hence, naively stripping them away does not meet my requirements.

For example, for this input,

\033[0;32;1mgreen_apple\033[0m 1 100
orange 20 19
pineapple 1000 87
avocado 4 30

The output I expect would be similar to

green_apple 1    100
orange      20   19
pineapple   1000 87
avocado     4    30

In the above output, "green_apple" should be colored according to the color codes from the input i.e. green. I'd like to know how this can be accomplished.

I've tried column, but it doesn't handle ANSI codes. The output of

echo '\033[0;32;1mgreen_apple\033[0m 1 100
orange 20 19
pineapple 1000 87
avocado 4 30' | column -t

is unfortunately

green_apple  1     100
orange                  20    19
pineapple               1000  87
avocado                 4     30

Notice the non-tablification.

Best Answer

I don't think there's such a command, you'd have to do by hand. Something like:

awk '
  {
    nf[NR]=NF
    for (i = 1; i <= NF; i++) {
      f[NR,i] = $i
      gsub(/\033\[[0-9;]*[mK]/, "", $i)
      len[NR,i] = l = length($i)
      if (l > max[i]) max[i] = l
    }
  }
  END {
    for (n = 1; n <= NR; n++) {
      for (i = 1; i < nf[n]; i++)
        printf "%s%*s", f[n,i], max[i]+1-len[n,i], ""
      print f[n,nf[n]]
    }
  }'
Related Question