首页 > 解决方案 > 计算总和

问题描述

假设我们有一个预算文件:budget.txt

练习是计算当月每个产品的总和列,还要计算最后一行的总计。您可以尝试在 shell 中执行此操作。它将如何运作?

对于 bash 脚本,您可以尝试使用 awk 和 bc 命令。

在此处输入图像描述

我创建了一个 shell 脚本

#!/bin/bash
echo -n " Please write the file name:" 
read file 
awk '{print $0}' $file

标签: awkbc

解决方案


为了展示 Ed 在请求文本时所说的内容...... XOne 工作解决方案

现在是 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
}

推荐阅读