AWK CSV Column Aggregation
Aggregate CSV columns with awk: per-group sums, counts, and computed ratios in one pass over streaming input.
Code
#!/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
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.