How to sort text file based on number after first letter

Viewed 215

I have a text file in linux that looks like this:

H-988   -0.5418829321861267 no
H-989   -0.5033702254295349 yes
H-990   -1.1516857147216797 hi
H-99    -0.5005123019218445 hello

I want to sort this file based on the number coming after the hyphen. So the order should be:

H-99    -0.5005123019218445 hello
H-988   -0.5418829321861267 no
H-989   -0.5033702254295349 yes
H-990   -1.1516857147216797 hi

I tried the grep sort command but it did not work. For example it puts 95 after 949 instead of before same goes for 99 and 990 as the example provided

2 Answers

You should sort as numerically,

sort --numeric-sort --field-separator "-" --key 2 some.txt

or a shorter version

sort -n -t "-" -k 2 some.txt

If the first field always has only two characters before the number, you can skip them:

sort -k1.3,1n ip.txt

-k1.3 tells sort to start considering the field (which is 1 here) only from the third character

Related