5

Given perhaps comma- or tab-delimited input, I'd like to present a series of appropriately padded columns to stdout, so I can easily scan columnar information which would otherwise present rather messily.

I've tried troff-based solutions and while the simple demos have worked, feeding the command actual input has resulted in bizarre errors. I've currently resorted to using a sed-based method hack which is rather slow...

EDIT: column is quite a useful tool, however it'd be really awesome if I the columns had, say, a pipe character (|) between them so they do not appear to "float" in space and I can easily distinguish where each starts.

PS. This post's title used to read 'ASCII "table"', not 'ASCII-art table'. Edited to try and remove confusion.

8

Assuming a CSV file, you can use column(1) like so:

column -ts, your_file

This is included in the bsdmainutils package on my Debian distribution, so I'm not sure how portable it is.

Two more things to note:

  1. The above example is simplistic; explore the man page for more details on how to format your output.
  2. It does not fare well with quoted fields containing commas. I.e., it would consider a,b,"c,d" as four columns not three.
  • Combining it with head is useful: column -ts, your_file | head – Abramodj Oct 18 '18 at 18:46
4

This will columnate the input file, adding a | character to surround each column.

 sed -e 's/^/| /' -e 's/,/,| /g' -e 's/$/,|/' inputfile | column -t -s,

Sample run (using a readily-available colon-delimited file):

$ head -4 /etc/passwd | tr : , | \
  sed -e 's/^/| /' -e 's/,/,| /g' -e 's/$/,|/' | column -t -s,

| root    | x  | 0  | 0  | root    | /root      | /bin/bash  |
| daemon  | x  | 1  | 1  | daemon  | /usr/sbin  | /bin/sh    |
| bin     | x  | 2  | 2  | bin     | /bin       | /bin/sh    |
| sys     | x  | 3  | 3  | sys     | /dev       | /bin/sh    |
4

If the tabular data is read in python somehow (in this example reading csv file with the Pandas module), the "tabulate" module is quite useful and simple.

import pandas
from tabulate import tabulate

data = pandas.read_csv('/tmp/foo.csv', index_col=0)
print(tabulate(data, headers=data.columns, tablefmt="grid"))

Which gives a nice output:

+-----+------+------+
|     |    A |    B |
+=====+======+======+
| foo | 1    |  0.2 |
+-----+------+------+
| bar | 3.14 | 10.9 |
+-----+------+------+

You can produce different styles

print(tabulate(data, headers=data.columns, tablefmt="fancy_grid"))

╒═════╤══════╤══════╕
│     │    A │    B │
╞═════╪══════╪══════╡
│ foo │ 1    │  0.2 │
├─────┼──────┼──────┤
│ bar │ 3.14 │ 10.9 │
╘═════╧══════╧══════╛
  • You can run the suggested code inside ipython (run ipython in your shell to start it) – Abramodj Oct 18 '18 at 18:35

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.