I’m wanting to create an alias called dir
for KSH that will show only the sub-directories in a cluttered directory with many files and directories.
I can output a single-column list of the directories, but I am having a problem converting the single-column list into a multi-column.
I want it to automatically determine the number of columns to use based on the length of the longest string and the width of the terminal window in the same way that the ls
command automatically creates tabbed columns.
Say I type the following at the terminal to give me a list of all the directories in the current directory:
ls -1Fa | grep /
When I pipe this output to column -t
, it doesn’t seem to have any effect… I get a list of 54 directories in a single column. I’ve also tried the common suggestion in other posts of piping to column -t -s $'t'
or column -t -s $'n'
, but it always results in a single list output. I’ve looked at the man pages and tried all the options, but I cannot get it to produce output similar to ls
.
I’ve also tried piping the output to pr with the following:
alias dir="ls -1Fa | grep / | pr -T -w $COLUMNS -6"
Unfortunately, this will always output 6 columns and if the terminal window is rather skinny (i.e. $COLUMNS is something small like 50) then long directory names are truncated at the beginning of the next column.
Can somebody answer why column
is not outputting the list into columns, or does somebody have a better solution using another tool such as sed, awk, perl?
Thanks for your help!
Advertisement
Answer
Really, all you need is
alias dir='ls -d */ .*/'
The trailing slash instructs ksh to only include directories in the glob expansion. And you get to piggy-back on how ls
formats into columns.
The answer to your question is that you’re using the wrong option for column
:
ls -1d */ .*/ | column -c $(tput cols)
column -t
pretty-prints the output, from
1 a b foobar baz
into
1 a b foobar baz
See the column
man page