Sort 'ls' output by name

Viewed 335796

Can you sort an ls listing by name?

13 Answers

My ls sorts by name by default. What are you seeing?

man ls states:

List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

For something simple, you can combine ls with sort. For just a list of file names:

ls -1 | sort

To sort them in reverse order:

ls -1 | sort -r

The beauty of *nix tools is you can combine them:

ls -l | sort -k9,9

The output of ls -l will look like this

-rw-rw-r-- 1 luckydonald luckydonald  532 Feb 21  2017 Makefile
-rwxrwxrwx 1 luckydonald luckydonald 4096 Nov 17 23:47 file.txt

So with 9,9 you sort column 9 up to the column 9, being the file names. You have to provide where to stop, which is the same column in this case. The columns start with 1.

Also, if you want to ignore upper/lower case, add --ignore-case to the sort command.

From the man page (for bash ls):

Sort entries alphabetically if none of -cftuSUX nor --sort.

You can try:

ls -lru

-u with -lt: sort by, and show, access time;

I got the contents of a directory sorted by name using below command:

ls -h

Related