ls command - switch the output rows to columns [closed]

Is there any way possible to change output of ls? Normally ls displays something like this:

something something1 something2 something3
something4 something5 something6 something7

and I want it to be like this:

1. something 5. something4
2. something1 6. something5
3. something2 7. something6
4. something3 8. something7

Is there any simple command to handle this case, without using loops and many lines of code?

3

4 Answers

ls -C sorts the files in the current directory in columns. In addition you can limit the width of the output with -w. ls -x sorts the output in lines. (man ls gives you a lot of other options.)

So in your example:

$ ls
something something2 something4 something6
something1 something3 something5 something7
$ ls -x # different ordering
something something1 something2 something3
something4 something5 something6 something7
$ ls -C # same as ls
something something2 something4 something6
something1 something3 something5 something7
$ ls -C -w 30 # same as ls -w 30
something something4
something1 something5
something2 something6
something3 something7

BTW: The output given in your question is certainly not the output of ls -l, but of ls.

To obtain 2 numbered columns, try:

ls | pr -2Tn

If you're planning on using this a lot and want to sequentially number the items listed, I'd consider making a script you can call when needed for this.

Here's a script that will do what you need. Save this to a shell script file... I've named mine 'numberlist.sh'. When you want to enumerate a list of files, change your working directory (cd) to that folder and then call this script with 'sh /filepath/numberlist.sh'

#!/bin/bash
#set a count variable for loop
i=1
#set a formatting for printf
fmt="%-15s\n"
#get working directory
curdir=${PWD}/
#get list of files only, exclude directories
onlyfiles=$(ls -p $curdir | grep -v /)
#create temp file to hold list
tmpfile=$(mktemp /tmp/filelist.XXXXXX)
#iterate through list of files
#number them and add to tempfile
for item in $onlyfiles; do printf "$fmt" "$i"."$item" >> "$tmpfile" i=$(($i+1))
done
#print the list in columnar order
cat $tmpfile | column
#remove the temp file
rm $tmpfile

JJoao's answer is something I wasn't aware of... seems you could do that as well. If you wanted to prevent listing directories however, you'd do:

ls -l | grep -v / | pr -2n

However, the formatting is different so it breaks long lists into "pages".

EDIT: missed the -T option. That will omit the "pages". So this is a good option

You Might Also Like