Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort numerically based on the first column

I have a tsv separated file, which i try to sort. I use sort -k1,1n, in order to sort numerically, on the first column.

but the result i get is the following, which is not what i wanted:

    061     data1
    2305    data2
    4080    data3
    9251    data4
    11844   data5
    238 data6
    264 data7
    33940   data8
    439 data9
    5640    otherdata
    682 help
    1264    moredata

expected output:

    061     data1
    238     data6
    264     data7
    439     data9
    682     help
    1264    moredata        
    2305    data2
    4080    data3
    5640    otherdata
    9251    data4
    11844   data5
    33940   data8

2 Answers

sort reads from stdin and command-line as well. Thus if you have a file you can:

sort < file
# or
sort file

if you want sort based on first column you can:

sort -k1 < file

But if fact it does affect the output since by default it does not care about numerical order. Thus you should add -n option:

  -n, --numeric-sort          compare according to string numerical value

and doing it like:

sort -k1 -n < file

it outputs:

061     data1
238 data6
264 data7
439 data9
682 help
1264    moredata
2305    data2
4080    data3
5640    otherdata
9251    data4
11844   data5
33940   data8

and if you provide it with -r it print in reverse order:

33940   data8
11844   data5
9251    data4
5640    otherdata
4080    data3
2305    data2
1264    moredata
682 help
439 data9
264 data7
238 data6
061     data1
like image 140
Shakiba Moshiri Avatar answered Nov 03 '25 00:11

Shakiba Moshiri


sort -k1 -n -t $'\t' input_file.tsv

like image 33
vrsoftcoza Avatar answered Nov 03 '25 00:11

vrsoftcoza