Suggested day 1020–30 minutesSafe in practice folder Module milestone

Mission 5 of 5

Awk Fundamentals

Calculate useful totals from a small inventory file.

Use awk to work with columns, records, field separators, conditions, and totals.

Outcome: Tables and CSV-like files become approachable from the terminal.

Mental model

Understand what is happening

awk sees each line as a record and each column as a field.

$0 is the whole line; $1 is first field; NF is number of fields; NR is line number.

Guided lab

Work through the mission

1

Print fields

Safe

Prints columns and line numbers.

Terminal
cd ~/linux-practice
echo -e 'Name Age City\nJohn 30 NYC\nJane 25 LA' > data.txt
awk '{print $1, $3}' data.txt
awk '{print NR, $0}' data.txt
2

CSV separator

Safe

Uses comma as a field separator and calculates values.

Terminal
echo -e 'Product,Price,Quantity\nApple,1.50,100\nBanana,0.75,200' > inventory.csv
awk -F, 'NR>1 {print $1, $2 * $3}' inventory.csv
3

Total calculation

Safe

Accumulates a total and prints it at the end.

Terminal
awk -F, 'NR>1 {total += $2 * $3} END {print total}' inventory.csv

Checkpoint

Verify the mission

The calculated total matches the source data.

Try it yourself

One step without a recipe

Build a report from a small CSV: filter the rows you need, transform one value, calculate a total, and save the verified result without changing the source.

Need a hint?

When you're staring at a CSV or a table in the terminal, reach for awk. It turns messy text into columns you can actually work with. Start with `awk '{print $1}'` to see the first column, then build from there. It's the Swiss Army knife for structured text.

Explain it back

Before you move on

  • What does NR mean?
  • How do you set comma as the field separator?

Shortcuts:Alt + ← previous lessonAlt + → next lessonAlt + H home? focus search