LS – How to Make ls Sort Underscore Characters First

localelssort

I like being able to name files and directories with an underscore prefix if it's something I want to keep separate from other files and directories at the same level. On Windows and Mac, for example, prefixing a file with an underscore sorts it to the top, in front of files starting with an alphanumeric character.

My googling has turned up that it has to do with the LC_COLLATE and my current locale (en_US). That's fine, though I really don't understand why en_US doesn't sort as expected.

Based on the ICU Collate demonstration site setting locale to en_US_POSIX certainly appears to have the sort order I'm looking for (you have to edit the sample data and add some underscores to test it out). But I don't really see how to apply this in my Linux shell.

Ideally, I'd like to be able to set up something in my bash config so that ls always sorts underscores first. How would I go about doing this?

Best Answer

If you can't get ls to sort the way you want, try shell expansion.

You can use file name patterns to run ls with a list of files that the shell already sorted, bypassing the method that ls uses.

ls -lf _* [!_]*

Assuming you have the files

_a a _b b _c c

this is like running

ls -lf _a _b _c a b c

Explanation:

_* is a shell pattern matching any file name beginning with an underscore, expanded in alphabetic order.

[!_]* matches any file name not beginning with an underscore, expanded in alphabetic order.

-f tells ls to not sort, because the shell already did.

More information: bash filename expansion

If there are directories in the current directory you will want to run the command like this to avoid ls listing files in the directories:

ls -lfd _* [!_]*
Related Question