'macOS Terminal: `ls` sorts results with capitalised names first
How can I fix this default sorting behaviour for ls
in the macOS Terminal? I want the results to be case-insensitive and alphabetised.
Here is an example to illustrate the current and desired behaviours when running ls
in a directory with the files/directories: Apple_, apple, Basket_, basket
Current behaviour:
Apple_
Basket_
apple
basket
Desired behaviour:
Apple_
apple
Basket_
basket
Does anyone know how to achieve this?
Solution 1:[1]
This no longer works
So @Yoric was very close, but the content of his function was a bit wrong: it would indeed sort the results alphabetically, but when using the `-la' flag, it would mess up the order of the "dot" files/directories (those beginning with a dot).
I found the correct solution by adapting the one in the following Stack Overflow post: Making the "ls" command sort "a" before "B" (vs a->b->A->B)
Steps:
- Open/create your shell profile file in your home directory (
~/
). (This file is automatically run every time you launch the shell). This would be:
.bash_profile
if not using a configuration framework.zshrc
if using zsh
- Add the following code
ls_sort() {
LC_COLLATE=en_US.utf8 ls "$@"
}
alias ls='ls_sort'
- Restart your Terminal
Thank you @Yoric for helping me to get to this solution!
Solution 2:[2]
You can sort like this:
$ mkdir testdir && cd testdir
$ touch apple basket Apple_ Basket_
$ ls | LC_COLLATE=C sort --ignore-case
The output (not exactly the expected result, actually):
Apple
apple_
basket
Basket_
UPDATE
To make it the default behavior of ls
, you can add this piece of code into the file ~/.bash_profile
(it will be effective after opening a new terminal window):
ls_sort() {
ls $1 | LC_COLLATE=C sort --ignore-case
}
alias ls='ls_sort'
You can actually name the alias lss
instead of ls
in the last line above, so you don't lose the original behavior of ls
.
Solution 3:[3]
The following works for me:
ls | sort -f
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Paul Dulaney |