AWK CSV Column Aggregation

Aggregate CSV columns with awk: per-group sums, counts, and computed ratios in one pass over streaming input.

BashCli Tooling

Code

bashsnippet
41 lines
#!/usr/bin/env bash
set -euo pipefail

# 输入形态:region,channel,orders,revenue_cents
readonly SAMPLE='eu,web,120,450000
eu,mobile,80,290000
na,web,95,310000
na,mobile,45,150000
apac,web,30,90000'

# 单遍聚合:分组求和与计数
aggregate() {
  awk -F',' '
    NR > 1 {
      orders[$1] += $3
      revenue[$1] += $4
      count[$1] += 1
      total_orders += $3
    }
    END {
      for (region in orders) {
        printf "%-6s 订单 %6d  营收 %10d  均单价 %8.0f\n", \
          region, orders[region], revenue[region], \
          revenue[region] / orders[region]
      }
      printf "TOTAL  订单 %6d\n", total_orders
    }
  '
}

echo "$SAMPLE" | aggregate

# 流式管道形态:配合 sort 输出前 N
echo "$SAMPLE" | awk -F',' 'NR > 1 { print $1, $4 }' \
  | sort -k2,2nr \
  | head -3

# 条件过滤加聚合一步完成
echo "$SAMPLE" | awk -F',' '$3 >= 80 { sum += $4; n++ }
  END { if (n > 0) printf "大渠道合计营收: %d(%d 个)\n", sum, n }'

How the snippet works

set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.

The work is delegated to readonly, awk and total_orders, chained through 5 pipes so each stage’s output feeds the next.

A helper function (aggregate) keeps the repeated logic out of the main flow.

Caveats

  • The pipeline is 5 stages deep — when it misbehaves, split the pipe and test the stages separately.

Statements that matter most here

for (region in orders) {
| sort -k2,2nr \
| head -3

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `awk`, `total_orders` must be available on the PATH environment variable; everything else is shell built-in syntax.