首页 > macos > macOS终端:`ls`首先使用大写字母对结果进行排序

macOS终端:`ls`首先使用大写字母对结果进行排序 (macOS Terminal: `ls` sorts results with capitalised names first)

问题

如何ls在macOS终端中修复此默认排序行为?我希望结果不区分大小写并按字母顺序排列。

下面是一个示例,用于说明在ls包含文件/目录的目录中运行时的当前和所需行为:Apple_,apple,Basket_,basket

目前的行为:

苹果_

篮_

苹果

期望的行为:

苹果_

苹果

篮_


有谁知道如何实现这一目标?

解决方法

所以@Yoric非常接近,但是他的函数内容有点错误:它确实会按字母顺序排序结果,但是当使用`-la'标志时,它会搞乱“点”文件/目录的顺序(那些以点开头)。

我通过调整以下Stack Overflow帖子中的一个找到了正确的解决方案使“ls”命令在“B”之前排序“a”(vs a-> b-> A-> B)

脚步:

  1. 在主目录(~/)中打开/创建shell配置文件。(每次启动shell时都会自动运行此文件)。这将是:

    • .bash_profile 如果不使用配置框架
    • .zshrc 如果使用zsh
  2. 添加以下代码


ls_sort() {
  LC_COLLATE=en_US.utf8 ls "$@"
}

alias ls='ls_sort'

  1. 重启你的终端

谢谢@Yoric帮助我找到这个解决方案!

问题

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?

解决方法

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:

  1. 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
  2. Add the following code


ls_sort() {
  LC_COLLATE=en_US.utf8 ls "$@"
}

alias ls='ls_sort'

  1. Restart your Terminal

Thank you @Yoric for helping me to get to this solution!

相似信息