Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

sorting

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 
like image 610
mahmood Avatar asked Jan 26 '12 08:01

mahmood


People also ask

How do I sort numerical order in Linux?

How to sort by number. To sort by number pass the -n option to sort . This will sort from lowest number to highest number and write the result to standard output. Suppose a file exists with a list of items of clothing that has a number at the start of the line and needs to be sorted numerically.

How do I sort a column according to Linux?

Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.

How do you sort text files in Linux?

To sort lines of text files, we use the sort command in the Linux system. The sort command is used to prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The operation of sorting is done based on one or more sort keys extracted from each line of input.

Which command is used to sort the numeric file?

The sort command sorts the contents of a file, in numeric or alphabetic order, and prints the results to standard output (usually the terminal screen). The original file is unaffected. The output of the sort command will then be stored in a file named newfilename in the current directory.


2 Answers

sort -nk4 file  -n for numerical sort -k for providing key 

or add -r option for reverse sorting

sort -nrk4 file 
like image 138
jaypal singh Avatar answered Sep 25 '22 02:09

jaypal singh


sort does not sort the file in-place. It outputs a sorted copy instead.

You need sort -n -k 4 out.txt > sorted-out.txt.

Edit: To get the order you want you have to sort the file with the numbers read in reverse. This does it:

cut -d' ' -f4 out.txt | rev | paste - out.txt | sort -k1 -n | cut -f2- > sorted-out.txt

like image 39
Joni Avatar answered Sep 25 '22 02:09

Joni