bash: print columns / a table

Posted Over 8 years ago. Visible to the public.

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

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
Claus-Theodor Riegg
Last edit
Over 3 years ago
Claus-Theodor Riegg
Keywords
indent, indentation
License
Source code in this card is licensed under the MIT License.
Posted by Claus-Theodor Riegg to makandra dev (2016-01-20 09:45)