Linux and Command-Line Basics
$ cat result.txt
cellA PASS 0.12
cellB FAIL 0.45
cellC PASS 0.08
cellD FAIL 0.31
$ awk '$2 == "FAIL" {print $1}' result.txtIn the session above, which of the following is printed by the last awk?
- AThe two lines cellB FAIL 0.45 and cellD FAIL 0.31
- BThe two lines FAIL and FAIL
- CThe two lines cellB and cellD
Show answer and explanation
Answer: C. The two lines cellB and cellD
awk splits each line at blanks into fields, written $1 for the first, $2 for the second and so on, with $0 for the whole line. "$2 == "FAIL"" is a pattern that selects lines whose second field is FAIL, and {print $1} is the action that prints the first field of such a line. The matching lines are those of cellB and cellD, so cellB and cellD are printed. awk treats a run of blanks as a single separator, so it can be easier than cut for extracting columns from output with uneven spacing.
- A. This is the result without {print $1}. If the action is omitted, the whole matching line ($0) is printed.
- B. This reads the fields as counted from 0. In awk, $1 is the first field and $0 is the whole line.
- C. Correct. The first field of each line whose second field is FAIL is printed.