Unix's 'ls' sort by name

Can you sort an ls listing by name?


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 alpha‐betically 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

ls from coreutils performs a locale-aware sort by default, and thus may produce surprising results in some cases (for instance, %foo will sort between bar and quux in LANG=en_US). If you want an ASCIIbetical sort, use

LANG=C ls

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.