William LAM
William LAM

Reputation: 455

How to sort alphanumeric column in unix with alphabet first and then numeric

Suppose I have a text file:

08174 C6517298
08184 P0785411
08184 K0255564
01234 56789012
09098 A9877756

I would like to sort the second column with alphabet first and then numeric

The expected outcome should be:

09098 A9877756
08174 C6517298
08184 K0255564
08184 P0785411
01234 56789012

I tried sort -gk2,2 and sort -k2,2, both do not give me the correct result. Please help.

Upvotes: 0

Views: 1457

Answers (2)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

Replace -gk2,2 with -k2g (you meant the -k option, right?) , then add -k2

sort -k2g -k2 file

The key definition syntax is F[.C][OPTS][,F[.C][OPTS]], where F is the field number (2, in particular); OPTS is one or more single-letter ordering options [bdfgiMhnRrV].

Note, you don't need the ,2, as it means to stop sorting at the second column, and the second column is the last.

The key option priorities are applied in the order you passed them in the command, i.e. -k2g is applied first, then -k2.

Upvotes: 1

P....
P....

Reputation: 18351

awk '{print $2,$0}' inputfile |sort -g |awk '{print $2,$3}'
09098 A9877756
08174 C6517298
08184 K0255564
08184 P0785411
01234 56789012

Upvotes: 1

Related Questions