Menu
CoddyTech

Columns With awk

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 25 of 39.

awk reads text line by line and splits each line into fields. $1 is the first field, $2 the second and $NF the last, since NF holds the number of fields. Fields are split at spaces unless -F names another separator.

awk '{ print $1, $NF }' scores.txt
awk -F, '$3 > 90 { print $1 }' scores.csv

On the line Ana math 92, the first command prints Ana 92. The second splits at commas and runs its block only on lines whose third field is over 90. With Ana,math,92 and Ben,math,78, it prints Ana.

awk -F, '{ sum += $3 } END { print sum }' scores.csv
awk -F, '{ printf "%-6s%3d\n", $1, $3 }' scores.csv

A variable such as sum starts at 0 and keeps its value from line to line. The END block runs once after the last line, so the first command prints 170. printf formats each line: %-6s pads the name to 6 characters, %3d right-aligns the number in 3, and \n ends the line.

challenge icon

Challenge

Medium

Write a script that lists the big orders in a CSV file and totals all of them.

  1. Open big.sh. The CSV file is its first argument. Each line is customer,item,amount, with no header.
  2. For each order whose amount is over 100 (100 itself is not), print the customer padded to 8 characters (%-8s) followed by the amount, in file order.
  3. Print Total: N, the sum of every amount in the file.
  4. Save the file.

Try it: run bash big.sh orders.csv. It prints:

Ana     250
Cara    480
Total: 845

Then run bash big.sh small.csv: no order is over 100, so it prints only Total: 15.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground