【问题标题】:Divide each row by max value in awk将每一行除以awk中的最大值
【发布时间】:2018-02-19 01:35:54
【问题描述】:

我试图将行除以该行中的最大值为(所有列都为 NA 的行)

    r1  r2  r3  r4
a   0   2.3 1.2 0.1
b   0.1 4.5 9.1 3.1
c   9.1 8.4 0   5

我明白了

    r1  r2  r3  r4
a   0   1   0.52173913  0.043478261
b   0.010989011 0.494505495 1   0.340659341
c   1   0.923076923 0   0.549450549

我尝试通过执行计算每行的最大值

  awk '{m=$1;for(i=1;i<=NF;i++)if($i>m)m=$i;print m}' file.txt > max.txt

然后将其作为最后一列粘贴到 file.txt 中

paste file.txt max.txt > file1.txt

我正在尝试执行一个代码,其中最后一列将划分该行中的所有列,但首先我需要格式化每一行,因此我被困在

awk '{for(i=1;i<NF;i++) printf "%s " $i,$NF}' file1.txt

我正在尝试打印该行的每个组合,然后在新行上打印下一行组合。但我想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • ..和?你已经得到这个还是你想要得到这个?到目前为止,你在 awk 中写了什么?什么有效/无效?举一个输入格式的最小例子。
  • 你想为全为零的行打印什么? 1s 或 NaNs 或 0s 还是别的什么?
  • 感谢您提出这个问题,我会将其添加到我的问题中

标签: shell awk scaling


【解决方案1】:

awk 来救援!

$ awk 'NR>1 {m=$2; for(i=3;i<=NF;i++) if($3>m) m=$3; 
             for(i=2;i<=NF;i++) $i/=m}1' file

    r1  r2  r3  r4
a 0 1 0.521739 0.0434783
b 0.0222222 1 2.02222 0.688889
c 1 0.923077 0 0.549451

【讨论】:

    【解决方案2】:

    关注awk 可能对您有所帮助:

    awk '
    FNR==1{
      print;
      next
    }
    {
      len=""
      for(i=2;i<=NF;i++){
         len=len>$i?len:$i};
      printf("%s%s", $1, OFS)
    }
    {
      for(i=2;i<=NF;i++){
         printf("%s%s",$i>0?$i/len:0,i==NF?RS:FS)}
    }
    '    Input_file
    

    说明:现在也在这里添加说明和解决方案:

    awk '
    FNR==1{  ##FNR==1 is a condition where it will check if it is first line of Input_file then do following:
      print; ##printing the current line then.
      next   ##next is awk out of the box keyword which will skip all further statements now.
    }
    {
      len="" ##variable named len(which contains the greatest value in a line here)
      for(i=2;i<=NF;i++){ ##Starting a for loop here starting from 2nd field to till value of NF which means it will cover all the fields on a line.
         len=len>$i?len:$i}; ##Creating a variable named len here whose value is $1 if it is NULL and if it is greater than current $1 then it remains same else will be $1
      printf("%s%s", $1, OFS) ##Printing the 1st column value here along with space.
    }
    {
      for(i=2;i<=NF;i++){ ##Starting a for loop here whose value starts from 2 to till the value of NF it covers all the field of current line.
         printf("%s%s",$i>0?$i/len:0,i==NF?RS:FS)} ##Printing current field divided by value of len varible(which has maximum value of current line), it also checks a conditoin if value of i equals to NF then print new line else print space.
    }
    '  Input_file          ##mentioning the Input_file name here.
    

    【讨论】:

    • @EdMorton,先生,现在完成了,谢谢您一如既往的指导 :)
    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多