bash - 排序命令无法正常工作,错误或功能?

标签 bash sorting

使用逗号作为字段分隔符时,排序命令无法正常工作:

文件:

cat /tmp/2.csv 
66.199.199.221,115645,0
207.233.77.147,120167,0
204.38.48.1,125767,0
83.144.97.50,127944,3
12.174.177.15,134080,0
195.76.177.90,138124,0
50.202.17.163,162618,0
66.64.209.30,163729,0
40.76.63.140,181976,0
207.241.237.163,2226,1854

观察 207.241.237.163,2226,1854 行:

排序:

sort -t, -nk 2  /tmp/2.csv 
66.199.199.221,115645,0
207.233.77.147,120167,0
204.38.48.1,125767,0
83.144.97.50,127944,3
12.174.177.15,134080,0
195.76.177.90,138124,0
50.202.17.163,162618,0
66.64.209.30,163729,0
40.76.63.140,181976,0
207.241.237.163,2226,1854

但它在使用 TSV 时工作正常:

sort -nk 2  /tmp/3.tsv 
207.241.237.163 2226    1854
66.199.199.221  115645  0
207.233.77.147  120167  0
204.38.48.1     125767  0
83.144.97.50    127944  3
12.174.177.15   134080  0
195.76.177.90   138124  0
50.202.17.163   162618  0
66.64.209.30    163729  0
40.76.63.140    181976  0

测试了不同版本的排序:

sort --version
sort (GNU coreutils) 8.21
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and Paul Eggert.

和:

sort (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and Paul Eggert.

最佳答案

您只需要为第二个字段设置键,即 -k2,2,否则如果您使用 -k2,则从第二个开始到结束的所有字段都将被视为键。

工作一个:

$ sort -t, -k2,2n file.txt 
207.241.237.163,2226,1854
66.199.199.221,115645,0
207.233.77.147,120167,0
204.38.48.1,125767,0
83.144.97.50,127944,3
12.174.177.15,134080,0
195.76.177.90,138124,0
50.202.17.163,162618,0
66.64.209.30,163729,0
40.76.63.140,181976,0

非工作的:

$ sort -t, -k2n file.txt 
66.199.199.221,115645,0
207.233.77.147,120167,0
204.38.48.1,125767,0
83.144.97.50,127944,3
12.174.177.15,134080,0
195.76.177.90,138124,0
50.202.17.163,162618,0
66.64.209.30,163729,0
40.76.63.140,181976,0
207.241.237.163,2226,1854

关于bash - 排序命令无法正常工作,错误或功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32717022/

相关文章:

java - 无法在 PHP 中使用 shell_exec() 传递 STDIN

java - java中如何计算有序数组的众数

java - 渲染器/排序优化

php - 如何每 3 小时在 shell 中运行相同的命令

linux - bash - 如何将换行符传递给脚本?

python - 如何按字母在前的字符串列排序?

ruby - 使用决胜局按长度对数组数组进行排序

java - 排序/比较不同的标准

bash - 具有浮点类型的数学多整数

c - "stack smashing detected"消息打印到哪个流?