【问题标题】:Handling ties when ranking in bash在 bash 中排名时处理平局
【发布时间】:2020-01-15 17:31:36
【问题描述】:

假设我有一个已经按如下排序的数字列表

100
222
343
423
423
500

我想要的是创建一个排名字段,以便为相同的值分配相同的排名

100   1
222   2
343   3
423   4
423   4
500   5

我一直在使用以下代码来模拟排名字段

awk '{print $0, NR}' file

下面给出了我,但从技术上讲,它是一个行号。

100   1
222   2
343   3
423   4
423   5
500   6

我该怎么做?我是bash 的绝对初学者,所以如果你能添加一点解释来学习,我将不胜感激。

【问题讨论】:

    标签: bash shell unix awk


    【解决方案1】:

    这是 awk 的工作:

    $ awk '{if($0!=p)++r;print $0,r;p=$0}' file
    

    输出:

    100 1
    222 2
    343 3
    423 4
    423 4
    500 5
    

    解释:

    $ awk '{           # using awk
    if($0!=p)          # if the value does not equal the previous value
        ++r            # increase the rank
    print $0,r         # output value and rank
        p=$0           # store value for next round
    }' file
    

    【讨论】:

    • 如果要排名的字段是$6,我会这样写吗? '{if($6!=p​​)++r;打印 $0,r;p=$6}'
    • 是的。很抱歉延迟回答,但就像你曾经说过的那样,@Gandalf,当你看到我时期待我。 ;D
    【解决方案2】:

    请您尝试关注一下。

    awk 'prev==$0{--count} {print $0,++count;prev=$1}' Input_file
    

    说明:为上述代码添加详细说明。

    awk '                 ##Starting awk code from here.
    prev==$0              ##Checking condition if variable prev is equal to current line then do following.
    {
      --count             ##Subtract count variable with 1 here.
    }
    {
      print $0,++count    ##Printing current line and variable count with increasing value of it.
      prev=$1             ##Setting value of prev to 1st field of current line.
    }
    ' Input_file          ##Mentioning Input_file name here.
    

    【讨论】:

      【解决方案3】:

      另一个awk

      $ awk '{print $1, a[$1]=a[$1]?a[$1]:++c}' file
      
      100 1
      222 2
      343 3
      423 4
      423 4
      500 5
      

      文件不需要排序的地方,例如在文件末尾添加一个新的423之后

      $ awk '{print $1, a[$1]=a[$1]?a[$1]:++c}' file
      
      100 1
      222 2
      343 3
      423 4
      423 4
      500 5
      423 4
      

      为观察到的新值增加排名计数器a,否则使用注册值作为键。因为c 被初始化为零,所以预先增加值。这将对相同的键使用相同的 rank 值,无论位置如何。

      【讨论】:

      • 我也喜欢这种方法。非常直观
      猜你喜欢
      • 2011-01-29
      • 2020-08-09
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      相关资源
      最近更新 更多