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.txt

In the session above, which of the following is printed by the last awk?

  1. AThe two lines cellB FAIL 0.45 and cellD FAIL 0.31
  2. BThe two lines FAIL and FAIL
  3. 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.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. Which of the following describes the files found when find /data -name "*.log" -mtime +7 -size +100M is run with GNU find?
  2. When stopping a process that has stopped responding, it is recommended to first use "kill <process ID>" and to use "kill -9 <process ID>" only if that does not end it. Which of the following is the reason?
  3. While a long-running ./sim.sh is running in a terminal, you want to use other commands in the same terminal. Which of the following is what happens when you press Ctrl+Z and then run bg?
  4. On a server reached over SSH, a long-running task was started with "./run.sh &", and when the connection was closed the task stopped too. Which of the following is the most appropriate way to start it so that it keeps running after the connection is closed?
  5. When the two lines above are run in a shell, which of the following are the characters shown?