Read more

bash: print columns / a table

Claus-Theodor Riegg
January 20, 2016Software engineer at makandra GmbH

Ever wondered how you can create a simple table output in bash? You can use the tool column for creating a simple table output.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Column gives you the possibility to indent text accurate to the same level. Pipe output to column -t (maybe configure the delimeter with -s) and see the magic happening.

detailed example

I needed to separate a list of databases and their corresponding size with a pipe symbol: |
Here is a example list.txt:

DB	Size_in_MB
foobar	11011.2
barfoo	4582.9
donkey	4220.8
shoryuken	555.9
hadouken	220.0
kong	214.8
super_mario_bros_p	211.1

The whitespaces were tabs. If you just replace them by cat list.txt | sed 's/\t/|/g' you get output like this:

DB|Size_in_MB
foobar|11011.2
barfoo|4582.9
donkey|4220.8
shoryuken|555.9
hadouken|220.0
kong|214.8
super_mario_bros_p|211.1

If you try to add more whitespace with cat list.txt | sed 's/\t/\t|\t/g' you won't be happy either:

DB	|	Size_in_MB
foobar	|	11011.2
barfoo	|	4582.9
donkey	|	4220.8
shoryuken	|	555.9
hadouken	|	220.0
kong	|	214.8
super_mario_bros_p	|	211.1

Solution

You can solve this problem with column. Use cat list.txt | sed 's/\t/,|,/g' | column -s ',' -t. The result looks like this:

DB                  |  Size_in_MB
foobar              |  11011.2
barfoo              |  4582.9
donkey              |  4220.8
shoryuken           |  555.9
hadouken            |  220.0
kong                |  214.8
super_mario_bros_p  |  211.1
Posted by Claus-Theodor Riegg to makandra dev (2016-01-20 10:45)