awk - 如何使用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。
解决方案
您能否尝试在 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.
推荐阅读
- node.js - 更新 URL 时,数据应该在前端过滤还是在后端过滤?
- pandas - 来自uproot的熊猫数据框中的字符串
- python - Celery SQS 任务失败后不会执行
- php - 由于奇怪的版本错误,无法在 macOS Catalina 上安装 PHP 7.3
- html - 通过 p 标签中的 xslt i 标签将 xml 转换为 html
- python - 无法使用 openpyxl 写入输出 excel 文件
- elasticsearch - 如何从 ElasticSearch 中检索脚本字段以及其他字段
- java - 如何通过路径在 LibGDX 中绘制自定义形状?
- c - 尝试拆分字符串并将它们放入数组时收到错误消息
- java - 如何通过 Android 应用程序发出 HTTP 请求