mahmood mahmood - 3 months ago 12
Linux Question

how to use Linux command Sort to sort the text file according to 4th column, numeric order?

I have a file like this(which is space delimited):

AX-18 Chr1_419085 1 41908545 T C -1 98 0.51
AX-19 Chr1_419087 1 41908740 T C 0 15 0.067
AX-20 Chr1_419087 1 41908741 T C 0 13 0.067


and I want to use
sort
command to sort the file according to 4th column. I looked it up everywhere on internet and I find different solutions which nun works!! I even find similar question in stackoverflow which the answer didn't work for me! so these are the commands that I'm using and are not working!

sort -n -k 4,1 out1.txt
sort -n -k 4 out1.txt
sort -n -k4 out1.txt
sort -nk4 out1.txt
sort +4 out1.txt


so after running all these commands I get this output( which is identical to my input):

AX-18 Chr1_419085 1 41908545 T C -1 98 0.51
AX-19 Chr1_419087 1 41908740 T C 0 15 0.067
AX-20 Chr1_419087 1 41908741 T C 0 13 0.067


I want to get an output like this:

AX-19 Chr1_419087 1 41908741 T C 0 15 0.067
AX-20 Chr1_419087 1 41908740 T C 0 13 0.067
AX-18 Chr1_419085 1 41908545 T C -1 98 0.51

Answer
sort -nk4 file

-n for numerical sort
-k for providing key

or add -r option for reverse sorting

sort -nrk4 file