如何结合升序和降序排序? [英] How to combine ascending and descending sorting?

查看:129
本文介绍了如何结合升序和降序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的文件(很多GB),看起来像

I have a very big file (many gigabytes) which looks like

input.txt

a|textA|2
c|textB|4
b|textC|5
e|textD|1
d|textE|4
b|textF|5

第一步,我想按第三行的降序对行进行数字排序,如果行与第三列的值相同,则必须按第一行的文本按升序对行进行排序.如果第一行和第三列的值相等,则必须按第二列的升序对它们进行排序.第二列保证是唯一且不同的.

At the first step, I want to sort lines numerically by the third column in descending order, and if lines have the same value of the third column, they must be sorted by the text of the first column – in ascending order. And if lines have equal values for their 1st and 3rd columns, they must be sorted by the 2nd column in ascending order. The second columns are guaranteed to be unique and different.

所以,我希望结果是:

desiredOutput.txt

b|textC|5
b|textF|5
c|textB|4
d|textE|4
a|textA|2
e|textD|1

我可以迈出第一步:

sort -t\| -bfrnk3 path/to/input.txt > path/to/output.txt

但是下一步是什么?也许结果可以在一次通过中实现?

But what is the next steps? And maybe the result might be achieved in a single pass?

编辑
我测试了sort -t '|' -k 3,3nr -k 1,1 -k 2,2 input.txt > output.txt.它给出以下"output.txt":

EDIT
I tested sort -t '|' -k 3,3nr -k 1,1 -k 2,2 input.txt > output.txt. It gives the following "output.txt":

b|textF|5
b|textC|5
c|textB|4
d|textE|4
a|textA|2
e|textD|1

这不是我想要的.

推荐答案

$ cat file
a|textA|2
c|textB|4
b|textC|5
e|textD|1
d|textE|4
b|textF|5
$ sort -t '|' -k 3,3nr -k 1,1 -k 2,2 file
b|textC|5
b|textF|5
c|textB|4
d|textE|4
a|textA|2
e|textD|1
$ sort -t '|' -k 3,3nr file
b|textC|5
b|textF|5
c|textB|4
d|textE|4
a|textA|2
e|textD|1
$

3,3nr中的

n表示数字排序,r表示反向.好像-k 1,1 -k 2,2是可选的,因为我猜sort默认情况下会以的顺序排序.

n in 3,3nr means numeric sorting, r means reverse. Seems like -k 1,1 -k 2,2 is optional as I guess sort would sort in the ascending order by default.

这篇关于如何结合升序和降序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆