awk - 计算总和
问题描述
假设我们有一个预算文件:budget.txt
练习是计算当月每个产品的总和列,还要计算最后一行的总计。您可以尝试在 shell 中执行此操作。它将如何运作?
- 程序/脚本应采用带有文件名的参数(不要在正文中硬编码)
- 做需要的事情
- 将输出打印到屏幕
- 如果某处的数据文件中有错误,程序/脚本应将其打印在屏幕上并终止。
对于 bash 脚本,您可以尝试使用 awk 和 bc 命令。
我创建了一个 shell 脚本
#!/bin/bash
echo -n " Please write the file name:"
read file
awk '{print $0}' $file
解决方案
现在是 awk 位的印刷精美、带注释的版本......
NR == 1 { # print the header line (the 1st row/record)
print
}
NR > 1 && $0 != "Total" { # for all but the last record (which starts with "Total")
rsum = 0 # zero a tally for the entire row
for (i = 2; i <= NF; i++) { # iterate over every column (field) from the 2nd to the last (NF)
a[i] += $i # add each fields value to an array (representing the column)
rsum += $i # add each fields value to the sum for the row
}
printf "%s\t%3d\n", $0, rsum # print each row with the sum of the row
fc = NF # store the number of fields for the next operation
a[NF + 1] += rsum # and tally the grand total
}
$1 == "Total" { # for the last row
printf "Total\t" # print "Total"
for (i = 2; i <= fc; i++) { # then the array values we added up above
printf "%3d\t", a[i]
}
printf "%3d\n", a[fc + 1] # followed by the grand total
}
推荐阅读
- windows - schtasks,只有在电脑连接网络时才启动任务?
- c# - ASP.Net Core Web MVC 中不生成 NLog 文件
- cors - 没有适用于 cors 和云功能的解决方案
- python - 当 plt.plot() 调用在其他单元格中完成时, plt.show() 为空
- python - PyCharm安装后的问题:动态链接库mkl_intel_thread.dll中找不到序数242
- multithreading - 线程数和 RAM 使用率之间一般有什么关系?
- php - 尝试使用 google-api-php-client 访问 GoogleSheet 但失败
- javascript - 使用 MVC5 Razor 在弹出窗口中显示来自 db 的二进制图像
- java - 在 RecyclerView 中查看来自 Firebase 存储的照片
- javascript - JavaScript根据div的高度和宽度将长字符串拆分为数组