Bird
0
0

You want to print the second field only for lines where the first field starts with 'a' or 'b'. Which awk command achieves this?

hard📝 Application Q15 of 15
Linux CLI - Text Processing
You want to print the second field only for lines where the first field starts with 'a' or 'b'. Which awk command achieves this?
Aawk '$1 ~ /^[ab]/ {print $2}' file.txt
Bawk '$1 == "a" || $1 == "b" {print $2}' file.txt
Cawk '$1 = "a" || $1 = "b" {print $2}' file.txt
Dawk '$1 ~ /a|b/ {print $2}' file.txt
Step-by-Step Solution
Solution:
  1. Step 1: Understand pattern for fields starting with 'a' or 'b'

    The regex /^[ab]/ matches strings starting with 'a' or 'b'. The operator ~ means regex match.
  2. Step 2: Check each option's correctness

    awk '$1 ~ /^[ab]/ {print $2}' file.txt uses correct regex and syntax. awk '$1 == "a" || $1 == "b" {print $2}' file.txt compares whole field to 'a' or 'b' exactly, not starts with. awk '$1 = "a" || $1 = "b" {print $2}' file.txt uses assignment '=' instead of comparison '=='. awk '$1 ~ /a|b/ {print $2}' file.txt matches anywhere 'a' or 'b' appears, not just start.
  3. Final Answer:

    awk '$1 ~ /^[ab]/ {print $2}' file.txt -> Option A
  4. Quick Check:

    Regex match start with a or b = awk '$1 ~ /^[ab]/ {print $2}' file.txt [OK]
Quick Trick: Use regex ^[ab] to match start of field [OK]
Common Mistakes:
  • Using = instead of == for comparison
  • Matching exact string instead of start
  • Using wrong regex without ^ anchor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Linux CLI Quizzes