对数字列进行排序

use*_*619 4 sort numeric-data

我试图根据特定位置对文件进行排序,但这不起作用,这是数据和输出。

~/scratch$ cat  id_researchers_2018_sample 
id - 884209 , researchers - 1
id - 896781 , researchers - 4
id - 901026 , researchers - 15
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 916197 , researchers - 1
~/scratch$ sort  -k 28,5 id_researchers_2018_sample 
id - 884209 , researchers - 1
id - 896781 , researchers - 4
id - 901026 , researchers - 15
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 916197 , researchers - 1
Run Code Online (Sandbox Code Playgroud)

我想按最后一列中的数字对其进行排序,如下所示:

~/scratch$ cat  id_researchers_2018_sample 
id - 884209 , researchers - 1
id - 896781 , researchers - 4
id - 901026 , researchers - 15
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 916197 , researchers - 1
~/scratch$ sort  -k 28,5 id_researchers_2018_sample 
id - 884209 , researchers - 1
id - 896781 , researchers - 4
id - 901026 , researchers - 15
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 916197 , researchers - 1
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 5

您打算按第 7 列进行数字排序。

这可以通过以下任一方式完成

$ sort -n -k 7 file
id - 884209 , researchers - 1
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 916197 , researchers - 1
id - 896781 , researchers - 4
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 901026 , researchers - 15
Run Code Online (Sandbox Code Playgroud)

或与

$ sort -k 7n file
id - 884209 , researchers - 1
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 916197 , researchers - 1
id - 896781 , researchers - 4
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 901026 , researchers - 15
Run Code Online (Sandbox Code Playgroud)

这些是等价的。

-n选项指定数字排序(与字典排序相反)。在上面的第二个示例中,n将 作为说明符/修饰符添加到第 7 列。

排序键列 的指定-k 7将对sort第 7 列开始的行(从第 7 列到末尾的行)进行排序。在本例中,由于第 7 列是最后一个,因此它仅表示这一列。如果这很重要,您可能想使用-k 7,7(“从第 7 列到第 7 列”)。

如果两个键比较相等,sort则将使用完整的行作为排序键,这就是为什么我们得到示例中前四行的结果。如果您想对第二列进行二次排序,您可以使用sort -n -k 7,7 -k 2,2, or sort -k 7,7n -k 2,2n(分别指定每列的比较类型)。同样,如果第七列第二列在两行之间比较相同,sort则将使用完整行的字典顺序比较。


要对字符位置 29(对应于示例数据中每行末尾的数值的第一位数字)进行数字排序:

$ sort -k 1.29n file
id - 884209 , researchers - 1
id - 904091 , researchers - 1
id - 905525 , researchers - 1
id - 916197 , researchers - 1
id - 896781 , researchers - 4
id - 908660 , researchers - 5
id - 908876 , researchers - 7
id - 910480 , researchers - 10
id - 901026 , researchers - 15
Run Code Online (Sandbox Code Playgroud)

意思是“对第一个字段的第 29 个字符-k 1.29n给出的键进行数字排序(向前,到行尾)”。

上面文本中使用-k 7,7n的 恰好等同于-k 7.1,7.1n.