Yun Huang
Yun Huang

Reputation: 4386

How to sort primary column with alphabet order then secondary column with numeric order?

Assuming there is a text file:

10  A   QAZ
5   A   EDC
14  B   RFV
3   A   WSX
7   B   TGB

I want to sort it with the second column as the main column with alphabet order and the first column as the secondary column with numeric order. The following is the expected result:

3   A   WSX
5   A   EDC
10  A   QAZ
7   B   TGB
14  B   RFV

I tried sort -k 2,2 -k 1,1 a.txt -n and sort -k 2,2 -k 1,1 a.txt but both give the wrong results. What should I solve this problem? Thanks.

Upvotes: 5

Views: 3203

Answers (2)

potong
potong

Reputation: 58371

This might work for you:

sort -k1.5,1.8 -k1.1,1.4n file

Upvotes: 0

choroba
choroba

Reputation: 241828

This should work:

sort -b -k2,2 -k1,1n

The -b is essential, without it, the output is wrong, since sort wrongly determines the position of the second column. See man sort (or here) for details.

Also, check your locale. They can influence how sort works.

Upvotes: 9

Related Questions