示例文件
$ cat tmp.txt #定义一个测试文本
baidu 100 5000
google 110 5000
sohu 100 4500
guge 50 3000
按照第三列排序和去重
# -k 参数: 指定列编号,首列编号1
$ sort -k 3 tmp.txt
guge 50 3000
sohu 100 4500
baidu 100 5000
google 110 5000
# -u 参数: 去重
guge 50 3000
sohu 100 4500
baidu 100 5000
符合我们的预期。
下面看一个不符合预期的。
按照第二列排序和去重
# 按第2列排序
$ sort -k 2 tmp.txt
sohu 100 4500
baidu 100 5000
google 110 5000
guge 50 3000
# 按第2列去重
$ sort -k 2 -u tmp.txt
sohu 100 4500
baidu 100 5000
google 110 5000
guge 50 3000
发现去重失败,第二列2个100都还在。为什么去重失败呢?
查帮助文档
版本 sort (GNU coreutils) 8.28
man sort 命令显示帮助文档。
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's
end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which
override global ordering options for that key. If no key is given, use the entire line as the key. Use --debug to diagnose incorrect key usage.
需要定义 start 和 end,F是列编号,C是字符在该列的位置编号;编号都是1开始的,stop位置默认是这一行结束。
看到这就破案了,如果不指定stop,则直接到本行的最后。
所以如果不是最后一列,就一定要指定stop列的编号。
正确的做法是 -k2,2 限定使用第二列去重。
$ sort -k 2,2 -u tmp.txt
baidu 100 5000
google 110 5000
guge 50 3000
按数字大小排序、倒序、多列排序
默认sort是按照ascii码排序,如果按照数字大小排序,则指定-n参数
$ sort -k 2,2 -n tmp.txt
guge 50 3000
baidu 100 5000
sohu 100 4500
google 110 5000
# 倒序使用-r
$ sort -k2,2 -n -r tmp.txt
google 110 5000
sohu 100 4500
baidu 100 5000
guge 50 3000
# 支持缩写
$ sort -k2,2nr tmp.txt
google 110 5000
baidu 100 5000
sohu 100 4500
guge 50 3000
# 按照第二列降序、第三列升序排序
$ sort -k2,2nr -k3n tmp.txt
google 110 5000
sohu 100 4500
baidu 100 5000
guge 50 3000