linux - Bash sort -nu 会导致意外行为

标签 linux bash shell sorting command

我的一位同事今天注意到排序命令有一些奇怪的行为,我想知道是否有人知道这个命令的输出是否是有意的?

给定文件:

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 选项,则排序将按照预期进行。

最佳答案

使用-nan empty number is zero :

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 

关于linux - Bash sort -nu 会导致意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42526860/

相关文章:

c - 如何在不截断任何单词的情况下使用缓冲区正确读取 stdin 的输入?

regex - 如何使用 bash 脚本和 sed 将字符串替换为换行符?

bash - 如何在不展平数组的情况下从 bash 数组中删除元素

linux - 如何杀死僵尸进程

linux - Bash Shell 为 getops 指定有效选项

python - 如何选择我在 Linux 上运行的 python 版本?

linux - 在 Debian jessie 上安装 Subversion 1.7

linux - 在启动脚本 linux 中运行 lap-request

linux - bash fork error (Resource temporary unavailable) 不会停止,每次我尝试终止/重启时都会出现

bash - $# 构造在 bash 中意味着什么?