Counting with awk
Beyond printing fields, awk can calculate. You can use variables, patterns, and
special blocks like END to produce summaries.
Summing a column
awk '{sum += $2} END {print sum}' readings.txt
This adds up every value in column 2 and prints the total after all lines are
processed. The END block runs once, after the last line.
Counting lines that match a pattern
awk '/error/ {count++} END {print count}' log.txt
The /error/ is a pattern: only lines containing "error" trigger the action. At the
end, we print how many matched.
Combining pattern and calculation
awk '$3 > 100 {print $1, $3}' data.txt
This prints field 1 and 3 only for lines where field 3 is greater than 100. Awk
patterns can be regex (/word/) or conditions ($2 == "alpha").
Mission: Cargo Weight Report
The station is approaching a gravity-assist manoeuvre and the pilot needs the cargo mass. cargo_weight.txt lists each item with its weight. In a new flight-deck folder, save the combined weight of all the cargo, the number alone, as total-weight.txt, and every item heavier than 100 with its weight as heavy.txt.
Expected result
flight-deck/total-weight.txt holds one number, and flight-deck/heavy.txt only the items over 100, each with its weight.