Format stdout as multi-column text

3

I'm trying to take some single column data and display it in a tty as columns, much like ls does. Basically, you can think of this as trying to take the output from ls -1 and make it look like the normal output of ls, where the number of columns and the space given to each column is optimized.

The column command can't easily be coerced into taking up a certain width, and the pr utility doesn't dynamically change the number of columns.

With all the text parsing commands available, I just can't believe there isn't some way to make this happen out of the box.

This would be a fairly complex little shell script, because in order to calculate the optimal column width you need to know how many items will be in your column (to calculate the length of the longest item), which you don't know until you figure out how many columns there will be, which depends on the width of each column. Because of the circular reasoning, it seems like iterative refinement is the only way to go. Not hard, but not a one-liner either. A built-in would be a much better solution if it exists.

Doug J

Posted 2012-03-20T00:16:09.093

Reputation: 608

Awk is commonly used for this. – technosaurus – 2012-03-20T03:18:49.997

1As you said the column width can't be known before all lines are needs to be examined. Most simple filters work as a pipe (except sort which uses tmp file). This makes it no so trivial and depending your case it could be easier for you to just writ this script based on what you exactly need. – Cougar – 2012-03-22T08:52:56.443

Answers

1

You'll want the pr command:

$ seq 25 | pr -t -5
1         6         11        16        21
2         7         12        17        22
3         8         13        18        23
4         9         14        19        24
5         10        15        20        25

glenn jackman

Posted 2012-03-20T00:16:09.093

Reputation: 18 546

0

You may be happy with

My Command | column -t 

See Easy way to columnize STDOUT (format text in columns)?

If you want to arrange several line into one, you may want to use sed command as such

ls -1 \
| sed -e 'N;N;N;s/\n/\t/g' \
| column -t 

In this case, you are making one line from four (three N; is four minus one ) then changing new line \n into tab (\t) for each new lines (\t) in buffer (g).

The last line column -t make it into optimal columns.

The ending \simply escape new line characters. You may want to type

ls -1 | sed -e 'N;N;N;s/\n/\t/g' | column -t 

instead.

Hope you are enjoying.

MUY Belgium

Posted 2012-03-20T00:16:09.093

Reputation: 265

I'm trying to deal with single column data that I want to put into multiple columns. column is only useful for arranging multi-column data. ie: ls -1 | column -t doesn't re-arrange things to look like ls – Doug J – 2014-05-28T16:58:14.890