awk splits each line into fields at spaces: $1, $2 … and $NF, the last. A condition before { print } picks the lines:
learner@reef:~$ cat register.log
08:00 INFO register started
09:20 ERROR drawer jammed
10:05 ERROR printer offline
learner@reef:~$ awk '$2 == "ERROR" { print $1, $NF }' register.log
09:20 jammed ← field 1 and the last field, where field 2 is ERROR
10:05 offlineThe program goes in single quotes, so bash leaves $1 alone: it is awk's field 1.
The requests that failed
At lunch, the web shop "broke at checkout". Its server writes a line for each request to ~/logs/access.log. Status 500 means the shop's own code failed:
The browser's name has spaces, so the seconds' field number changes. They are always $NF.
-
Write
~/server-errors.sh LOG. For each request with status500, it prints the path and the seconds. Read the log from"$1". -
Run
chmod u+x ~/server-errors.sh, then run it:textlearner@reef:~$ ./server-errors.sh ~/logs/access.log /checkout 3.412 …
Add up a column
-F, splits at commas. total += $3 adds field 3 on each line, and END { } runs once, after the last line. -v shop=north hands awk a value from outside:
learner@reef:~$ cat waste.csv
north,sourdough,3 ← shop, item, how many thrown away
south,croissant,5
east side,sourdough,2
north,scone,4
learner@reef:~$ awk -F, -v shop=north '$1 == shop { total += $3 } END { print total }' waste.csv
7A line of ~/sales.csv is 07:33,north,croissant,2.40: time, shop, item, price.
- Write
~/shop-sales.sh SHOP FILE. It prints the total price of that shop's lines. Pass the shop in with-v shop="$1", and read the file from"$2". - Make it runnable, then run
./shop-sales.sh north ~/sales.csv. - Run
./shop-sales.sh "east side" ~/sales.csv.
Objectives
./server-errors.sh ~/logs/access.logprints the path and the seconds of every500../shop-sales.sh north ~/sales.csvprints25.- It works for
east side, which has a space.