Sorting numerically but not alphabetically when nu

2019-08-15 07:59发布

I have a file like this:

A 0.77
C 0.98
B 0.77
Z 0.77
G 0.65

I want to sort the file numerically in descending order. I used this code:

sort -gr -k2,2 file.txt

I obtain this:

C 0.98 
Z 0.77
B 0.77
A 0.77
G 0.65

In my real file I have several columns with the same number and they are ordered alphabetically. What I want is to sort numerically but not alphabetically when the numbers are equal, I want to obtain those columns unsorted alphabetically:

C 0.98
B 0.77  
Z 0.77
A 0.77
G 0.65

But any random order is fine.

2条回答
该账号已被封号
2楼-- · 2019-08-15 08:22

You can use this sort:

sort -k2rn -k1R file

C 0.98
B 0.77
Z 0.77
A 0.77
G 0.65

There are 2 sort options used:

  • -k2rn: First sort key is column 2; numerical, reverse
  • -k1R: Second sort key is column 1; random
查看更多
虎瘦雄心在
3楼-- · 2019-08-15 08:44

One in GNU awk that preserves the order of the first field (random in, equally random out):

$ awk ' {
    a[$2]=a[$2] (a[$2]==""?"":FS) $1       # append $1 values to hash, indexed on $1
}
END {
    PROCINFO["sorted_in"]="@ind_num_desc"  # set for traverse order for index order...
    for(i in a) {                          # ... and use it here
        n=split(a[i],b)
        for(j=1;j<=n;j++)                  # preserve the input order
            print b[j],i                   # output
    }
}' file
C 0.98
A 0.77
B 0.77
Z 0.77
G 0.65

Testing reverse order:

$ tac file | awk '# above awk script'
C 0.98
Z 0.77
B 0.77
A 0.77
G 0.65
查看更多
登录 后发表回答