Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by column linux

Tags:

linux

sorting

I have a file with columns shown below:

chr1  91.4062
chr10  97.9150
chr11 116.7630
chr12 106.7870
chr13 116.1050
chr14 126.2180
chr15 110.2320
chr16  96.8076
chr17 113.5970
chr18  86.1011
chr19 130.6770
chr2 111.4620
chr20  68.4864
chr21 107.0810
chr22 140.7750
chr23 110.9590
chr24  68.4785
chr25 102.2080
chr26  72.2762
chr27  96.2213
chr28  85.5570
chr29 126.3800
chr3 116.1830
chr30  89.5663
chr31  89.1227
chr32 128.6190
chr4 117.3620
chr5  78.1921
chr6  85.4915
chr7 107.2620
chr8 112.9560
chr9  69.0250
chrX  66.0736

I want to sort it based on 1st column and the output should look like below:

chr1 91.4062
chr2 111.4620
chr3 116.1830
chr4 117.3620
chr5 78.1921
chr6 85.4915
chr7 107.2620
chr8 112.9560
chr9 69.0250
chr10 97.9150
chr11 116.7630
chr12 106.7870
chr13 116.1050
chr14 126.2180
chr15 110.2320
chr16 96.8076
chr17 113.5970
chr18 86.1011
chr19 130.6770
chr20 68.4864
chr21 107.0810
chr22 140.7750
chr23 110.9590
chr24 68.4785
chr25 102.2080
chr26 72.2762
chr27 96.2213
chr28 85.5570
chr29 126.3800
chr30 89.5663
chr31 89.1227
chr32 128.6190
chrX 66.0736

Any solution using linux commands would be helpful.

like image 985
chas Avatar asked Aug 19 '13 08:08

chas


People also ask

How do I sort a specific column in Linux?

Columns or fieldsUse the -k option to sort on a certain column. For example, use " -k 2 " to sort on the second column.

How do I sort by one column in bash?

Sort allows us to sort a file by columns by using the -k option. Let us start by creating a file with more than one column. In sort, we separate a column by a single space.

How do I sort a column in vim?

Sorting text in Vim is easy! Select the text, then press : , type sort , then hit enter! It'll sort the whole document by default, but you can enter a range too.


1 Answers

sort -V to the rescue:

sort -V file

From man sort:

-V, --version-sort

natural sort of (version) numbers within text


In case you do not have the -V option in your sort command, there is an alternative: sort by first column starting on 4th character (-k1.4) and then sort numerically (-n).

sort -k1.4 -n file

In both cases the output is as follows:

chrX  66.0736
chr1  91.4062
chr2 111.4620
chr3 116.1830
chr4 117.3620
...
chr26  72.2762
chr27  96.2213
chr28  85.5570
chr29 126.3800
chr30  89.5663
chr31  89.1227
chr32 128.6190
like image 170
fedorqui 'SO stop harming' Avatar answered Oct 07 '22 21:10

fedorqui 'SO stop harming'