← All Exercises

Sum a CSV Column with awk

basicbash~20min

Background

Quick reconciliation often happens in the shell. awk handles field splitting and numeric validation without loading the file into a database.

Problem

Given a CSV file whose third column holds decimal amounts, sum the column while skipping the header and reject the file if any data row has a non-numeric amount.

Input

A CSV file with a header row and comma-separated fields; column 3 contains amounts such as 120.50, optionally wrapped in double quotes.

Output

A single line rows=<n> total=<sum> with the sum formatted to two decimals, or a non-zero exit and an error on the first invalid amount.

Sample tests

Sample 1

Input: date,region,amount
2026-09-01,emea,120.50
2026-09-02,apac,80
2026-09-03,emea,99.50
Expected: rows=3 total=300.00

Sample 2

Input: date,region,amount
2026-09-01,emea,12x
Expected: invalid amount on line 2: 12x
and exit status 1

Your solution

Learning objective

Use field separators, numeric regex validation, stderr redirection, and END-block error propagation in awk.