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
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.
Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.
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.
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.
sort -nk4 file -n for numerical sort -k for providing key
or add -r option
for reverse sorting
sort -nrk4 file
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With