View Full Version : How can I sort the output of ls?

4th March 2008, 02:52 AM
ls can list all the files and directories. Can I sort the output by time, size, or owner?

4th March 2008, 02:56 AM
This info help? http://www.linuxcommand.org/lts0030.php#ls

4th March 2008, 02:58 AM

ls --help


4th March 2008, 03:19 AM
Is it weird that I actually adore these sorts of "how to do xyz from bash" questions? (For you smart ones, that's rhetorical. :p)

I don't know if/how you can do it with a straight ls command (see man ls if it has any built-in functions), but I did find you can pipe ls's output over to another command, sort, which sorts based on columns in plain text input (like the output of ls -l)

[root@pollux log]# ls -al | sort -k 6,6 -k 7,7
total 5508
drwx------ 2 root root 4096 2006-12-01 06:54 ppp
drwxr-xr-x 2 torrent torrent 4096 2007-03-25 08:49 bittorrent
drwxr-xr-x 2 ntp ntp 4096 2007-09-24 09:40 ntpstats
drwxr-xr-x 2 root root 4096 2007-09-27 17:06 vbox
drwxr-x--- 2 root root 4096 2008-01-11 15:47 audit
-rw------- 1 root root 24888 2008-01-24 01:26 anaconda.syslog
-rw------- 1 root root 29884 2008-01-24 01:26 anaconda.log
-rw------- 1 root root 41452 2008-01-24 01:26 anaconda.xlog

So, ls -al does long formatted output of ls with hidden files, and then I piped them over to sort and sorted first by column 6 (date) and then by column 7 (time). I tried, and you can do this with anything that ls outputs - name (redundant alone with the ls command, but if you want to sort by criteria a then b), ownership, octal permissions.

See man sort and man ls.

That help?

more on piping (|, the key usually above enter, used for I/O control in bash), if you're not familiar:

4th March 2008, 06:57 AM
What's wrong with "ls -lt" to sort by date? Or "ls -lrt" to sort by date newest last.

do "man ls" or "info ls" to get the manual for ls. Same for any other basic unix command.