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.csvOn 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.csvA 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
MediumWrite a script that lists the big orders in a CSV file and totals all of them.
- Open
big.sh. The CSV file is its first argument. Each line iscustomer,item,amount, with no header. - 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. - Print
Total: N, the sum of every amount in the file. - Save the file.
Try it: run bash big.sh orders.csv. It prints:
Ana 250
Cara 480
Total: 845Then run bash big.sh small.csv: no order is over 100, so it prints only Total: 15.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter5Text Power Tools
Finding FilesBatch Work With xargsEditing Text With sedColumns With awkRecap - Log SummaryPractice on your own: Terminal playground