How to sort alphanumeric column in unix with alpha

2019-09-15 02:39发布

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.

2条回答
Viruses.
2楼-- · 2019-09-15 03:04

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.

查看更多
闹够了就滚
3楼-- · 2019-09-15 03:07
awk '{print $2,$0}' inputfile |sort -g |awk '{print $2,$3}'
09098 A9877756
08174 C6517298
08184 K0255564
08184 P0785411
01234 56789012
查看更多
登录 后发表回答