排序(默认和数字选项 -n 之间的区别)

Mus*_*edi 1 sort

根据手册页,我们对 sort 命令的 --numeric-sort 选项进行了以下描述。

-n, --numeric-sort
              compare according to string numerical value
Run Code Online (Sandbox Code Playgroud)

我假设,通过字符串数值,我们的意思是通过其 ASCII 值连续比较每个字符串字符?

信息页阅读

‘-n’
‘--numeric-sort’
‘--sort=numeric’
     Sort numerically.  The number begins each line and consists of
     optional blanks, an optional ‘-’ sign, and zero or more digits
     possibly separated by thousands separators, optionally followed by
     a decimal-point character and zero or more digits.  An empty number
     is treated as ‘0’.  The ‘LC_NUMERIC’ locale specifies the
     decimal-point character and thousands separator.  By default a
     blank is a space or a tab, but the ‘LC_CTYPE’ locale can change
     this.

     Comparison is exact; there is no rounding error.

     Neither a leading ‘+’ nor exponential notation is recognized.  To
     compare such strings numerically, use the ‘--general-numeric-sort’
     (‘-g’) option.
Run Code Online (Sandbox Code Playgroud)

在阅读了这两个文档后,我仍然没有看到明确解释 -n 选项使用哪种排序规则。

--numeric-sort 选项与默认选项有何不同?我天真的猜测是数字优先于字母,但我没有在文档中阅读这个。

哪些文档明确说明了这一点,即我可以通过查找文档在哪里找到这些信息?

mat*_*tdm 5

当您有多位数字时,请sort -n考虑整个数字;默认情况下文件

3
2
1
20
30
Run Code Online (Sandbox Code Playgroud)

排序是这样的:

1
2
20
3
30
Run Code Online (Sandbox Code Playgroud)

这可能不是你想要的。使用-n,您将获得:

1
2
3
20
30
Run Code Online (Sandbox Code Playgroud)

数字排序还处理负数、小数点和千位分隔符(由您的语言环境决定)。如果有尾随的“非数字”文本,它会在排序顺序中被忽略。如果该行以非数字内容开头,则该行计为 0。

更准确地说,逻辑是这样的:(主)排序键是一个初始数字字符串。(即,“数字从每一行开始”。)该字符串被定义为由可能的空格、减号、零个或多个数字以及可能的.,(或其他)组成。尾随字母不考虑在内——它们不是“数字”的一部分。如果该行不以数字开头,则将其视为等于 0的不可见(“空”)数字。(或“零位数的数字”。)

因此,在对“数字”进行-k排序后(比较使用提供排序键),如果有任何剩余的行,这些行将使用默认 sort 进行排序。(即,1a之前1b- 和1a20之前1a3。)行以这种方式排序,而不是排序键之外的行,这在这种情况下会产生一些奇怪的行为(0cookies排序之前 biscuits- 对于二级排序,没有“不可见的 0”添加)。

通常,-n当您真正想要对由数字组成的行(或字段)进行排序时使用。如果你有一堆不是数字的东西,或者数字与其他字符串混合在一起,你仍然会得到一致的结果,但它可能不是你想要的。

如果您有字母和数字(和包含两条线)混合,你可能更喜欢-V,这确实一个版本排序根据特殊规则它们将字符串转换成逻辑组件-但要小心,因为这将使1.10 1.9