问题
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?
回答1:
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.
回答2:
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_profileif not using a configuration framework.zshrcif 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!
来源:https://stackoverflow.com/questions/53833833/macos-terminal-ls-sorts-results-with-capitalised-names-first