【问题标题】:Awk print specific lines where a column has a max value greater than 0.5awk 打印列的最大值大于 0.5 的特定行
【发布时间】:2019-11-25 23:11:47
【问题描述】:

我有一个制表符分隔的文件,看起来像这样,有 5 列。

temp1   56   09   34,54,65,6   file1
temp2   45   23   4,55,11,7,8,4,7   file2
temp3   123  56   0.01,0,50,4,4,4,6,7,1,3,44,67,8  file3
temp4   11   56   0.006,0.006,0.006  file4
temp5   10   123  0.00001,0.005,0.004 file5

我希望能够拆分第 4 列,并查看列表中的每个值,如果第 4 列中该列表的最大值大于 0.5,则打印出整行。

所以输出将是:

temp1   56   09   34,54,65,6   file1
temp2   45   23   4,55,11,7,8,4,7   file2
temp3   123  56   0.01,0,50,4,4,4,6,7,1,3,44,67,8  file3

这是我到目前为止所尝试的:

cat inputFile.txt|awk 'BEGIN {FS="\t"}; NR>1 {print $4}'|awk '{split($1,a,","); if (max(a)>0.5) print $0}'

但我已经变得困惑了。

【问题讨论】:

    标签: awk


    【解决方案1】:

    请您尝试关注一下。

    awk '
    {
      num=split($4,array,",")
      for(i=1;i<=num;i++){
        max=max>array[i]?max:array[i]
      }
      if(max>0.5){
        print
      }
      max=""
    }
    ' Input_file
    

    您无需将catawk 解决方案一起使用,因为awk 可以自行读取Input_file。

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

    awk '                                   ##Starting awk program here.
    {
      num=split($4,array,",")               ##Splitting 4th column into an array named array with delimiter of comma here.
      for(i=1;i<=num;i++){                  ##Starting a for loop from i=1 till value of num(which is total number of elements after we split 4th column with delimiter comma).
        max=max>array[i]?max:array[i]       ##Creating a variable named max whose value is max or array with index i whichever is greater each time cursor comes here.
      }
      if(max>0.5){                          ##Checking condition here if max variable is grater than 0.5 as per OP need then do following.
        print                               ##Printing current line.
      }
      max=""                                ##Nullifying max variable value so that next cycle it should not take previous values.
    }
    ' Input_file                            ##Mentioning Input_file name here.
    

    【讨论】:

    • 嗨。我需要它用于第 4 列中的所有值,因此有些行有 10 个逗号分隔值,其他行有 3 个,其他行可以有 2 个。我需要列表中的最大值。
    • @Rk_23,好的,请检查我的更新,然后让我知道吗?
    • 无需使用FS="\t"。任何空格/制表符都是awk 的默认行为,因此如果它的空格、多个空格或制表符,第一个解决方案将起作用。
    • @RavinderSingh13 谢谢大家。该解决方案将我们引向正确的方向并回答了我的疑问!谢谢大家!
    【解决方案2】:
    $ cat tst.awk
    BEGIN { FS="\t"; tgt=0.5 }
    {
        split($4,vals,/,/)
        max = vals[1]
        for (i in vals) {
            max = (vals[i] > max ? vals[i] : max)
        }
    }
    max > tgt
    
    $ awk -f tst.awk file
    temp1   56      09      34,54,65,6      file1
    temp2   45      23      4,55,11,7,8,4,7 file2
    temp3   123     56      0.01,0,50,4,4,4,6,7,1,3,44,67,8 file3
    

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 2022-11-16
      • 2020-08-28
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多