Bash sort -nu 导致意外行为
Bash sort -nu results in unexpected behaviour
我的一个同事今天注意到 sort 命令有一些奇怪的行为,我想知道是否有人知道这个命令的输出是否是有意的?
给定文件:
ABC_22
ABC_43
ABC_1
ABC_1
ABC_43
ABC_10
ABC_123
我们希望用数字排序对文件进行排序,并使其唯一,所以我们运行:
sort file.txt -nu
输出为:
ABC_22
现在,我们知道数字排序在这种情况下不起作用,因为行不是以数字开头的(没关系,这只是一个更大的脚本的一部分),但我会预料到一些事情更多的是:
ABC_1
ABC_10
ABC_123
ABC_22
ABC_43
有谁知道为什么不是这样?如果单独给出 -u 或 -n 选项,则排序就像人们期望的那样。
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’.
所有这些行的行首都有一个空数字,因此由于 sort
的数字唯一性,它们都是零。如果每一行都以相同的数字开头,比如 1
,效果是一样的。您应该明确指定包含数字的字段,或使用版本排序 (-V
):
$ sort -Vu foo
ABC_1
ABC_10
ABC_22
ABC_43
ABC_123
您没有将 GNU sort
的第二个字段的取消限制指定为
sort -nu -t'_' -k2 file
ABC_1
ABC_10
ABC_22
ABC_43
ABC_123
标记 -n
用于数字排序,-u
用于唯一行和 key 部分是将 de-limiter 设置为 _
并在 _
之后的第二个字段上排序 -k2
。
我的一个同事今天注意到 sort 命令有一些奇怪的行为,我想知道是否有人知道这个命令的输出是否是有意的?
给定文件:
ABC_22
ABC_43
ABC_1
ABC_1
ABC_43
ABC_10
ABC_123
我们希望用数字排序对文件进行排序,并使其唯一,所以我们运行:
sort file.txt -nu
输出为:
ABC_22
现在,我们知道数字排序在这种情况下不起作用,因为行不是以数字开头的(没关系,这只是一个更大的脚本的一部分),但我会预料到一些事情更多的是:
ABC_1
ABC_10
ABC_123
ABC_22
ABC_43
有谁知道为什么不是这样?如果单独给出 -u 或 -n 选项,则排序就像人们期望的那样。
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’.
所有这些行的行首都有一个空数字,因此由于 sort
的数字唯一性,它们都是零。如果每一行都以相同的数字开头,比如 1
,效果是一样的。您应该明确指定包含数字的字段,或使用版本排序 (-V
):
$ sort -Vu foo
ABC_1
ABC_10
ABC_22
ABC_43
ABC_123
您没有将 GNU sort
的第二个字段的取消限制指定为
sort -nu -t'_' -k2 file
ABC_1
ABC_10
ABC_22
ABC_43
ABC_123
标记 -n
用于数字排序,-u
用于唯一行和 key 部分是将 de-limiter 设置为 _
并在 _
之后的第二个字段上排序 -k2
。