首页 > 解决方案 > 如何使用awk为每一行使用值的总和

问题描述

我有一个小 txt 文件:

Josh 10
Bill 10
Samanda 30

所有 nums 的总和是 50。如何使用这个总和来划分每一行的值?

0.2 # 10/50
0.2 # 10/50
0.6 # 30/50

我的 awk 脚本没有按预期工作:

BEGIN {
sum += $2;
}
{
print $2/sum
}

它返回 0。

标签: awk

解决方案


您能否尝试在 GNU 中使用显示的示例进行跟踪、编写和测试awk

awk '
{
  val[NR]=$2
  sum+=$2
}
END{
  for(i=1;i<=NR;i++){
    print sum?val[i]/sum:0
  }
}
' Input_file

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

awk '                            ##Starting awk program from here.
{
  val[NR]=$2                     ##Creating array val whose index is  current line number and value is 2nd field of current line.
  sum+=$2                        ##Creating sum which has 2nd column value in it which is keep on getting added in it.
}
END{                             ##Starting END block of this code here.
  for(i=1;i<=NR;i++){            ##Starting a for loop from i 1 to till value of count here.
    print sum?val[i]/sum:0       ##Printing val[i]/sum value here if sum is NOT NULL else printing 0 here.
  }
}
' Input_file                     ##Mentioning Input_file name here.

推荐阅读