Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 547
Yun Huang Avatar asked Aug 06 '12 15:08

Yun Huang


1 Answers

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.

like image 169
choroba Avatar answered Nov 15 '22 04:11

choroba