M HYPE SPLASH
// updates

How do I sort a file based on both letters and numbers?

By John Campbell

A file with this content:

abc[0]
abc[100]
abc[101]
.
.
abc[127]
abc[19]
abc[1]
.
.
abc[9]
xyz[0]
xyz[100]
xyz[101]
.
.
xyz[127]
xyz[19]
xyz[1]
.
.
xyz[9]

I want to retain the alphabetical order but order according to the content in the brackets numerically.

abc[0]
abc[1]
abc[2]
.
.
abc[127]
xyz[0]
xyz[1]
xyz[2]
.
.
xyz[127]
0

1 Answer

GNU sort's --version-sort should do that for you:

sort --version-sort file

Otherwise, use [ as the separator and sort by the first field and then numerically by the second:

sort -t'[' -k1,1 -k2n file

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy