Linux BASH 中多列文件的反向排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14120846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:10:12  来源:igfitidea点击:

Reverse sort order of a multicolumn file in BASH

linuxbashunixsortingawk

提问by Valerio D. Ciotti

I've the following file:

我有以下文件:

1 2 3
1 4 5
1 6 7
2 3 5
5 2 1

and I want that the file be sorted for the second column but from the largest number (in this case 6) to the smallest. I've tried with

我希望文件按第二列排序,但从最大数字(在本例中为 6)到最小数字。我试过

sort +1 -2 file.dat

but it gives me the inversed order.

但它给了我相反的顺序。

The results should be:

结果应该是:

1 6 7
1 4 5
2 3 5
5 2 1
1 2 3

采纳答案by Danstahr

sort -nrk 2,2

does the trick.

诀窍。

n for numeric sorting, r for reverse order and k 2,2 for the second column.

n 用于数字排序,r 用于逆序,k 2,2 用于第二列。

回答by Brian Agnew

Have you tried -r ? From the man page:

你试过 -r 吗?从手册页

-r, --reverse

          reverse the result of comparisons

-r, --reverse

          reverse the result of comparisons

回答by Chris Seymour

As mention most version of sorthave the -roption if yours doesn't try tac:

如前所述,如果您不尝试,大多数版本sort都有-r选项tac

$ sort -nk 2,2 file.dat | tac 
1 6 7
1 4 5
2 3 5
5 2 1
1 2 3

$ sort -nrk 2,2 file.dat 
1 6 7
1 4 5
2 3 5
5 2 1
1 2 3

tac - concatenate and print files in reverse

tac - 反向连接和打印文件