sorting left-justified numeric values

I have a file which looks roughly like this:

996 mmmmmmm
996 xxxxxxxxxxxxx
99600 ssssssssss
9964 fffffffffffff

and would like to sort it numerically on the first field. I tried:

    sort -nr --key=1 ....

The output I get is:

99600 ssssssssss
9964 fffffffffffff
996 mmmmmmm
996 xxxxxxxxxxxxx

The output I would like to have:

996 mmmmmmm
996 xxxxxxxxxxxxx
9964 fffffffffffff
99600 ssssssssss

Of course I can solve this by writing a one-liner in, say, Perl or Ruby, but I wonder why my approach had not worked, and how I can use the genuine 'sort' command to achieve my goal.

Drop the -r option.

sort -n --key=1 ....
1 Like

Arrrrrrrrrrrgh :wall:

Thanks a lot, I think it's time for going home.......

Ronald

Unless you are intentionally restricting the portability of your code, it's unwise to use GNU long options when there exists a traditional, ubiquitous, and equivalent short option. sort -n -k1 will work just about anywhere (Linux, Solaris, AIX, HP-UX, OS X, FreeBSD, NetBSD, OpenBSD, et al). While sort -n --key=1 is unlikely to work beyond GNU/Linux.

If portability is not a concern, please disregard this post.

Regards,
Alister

1 Like