0
0
Bash Scriptingscripting~20 mins

awk field extraction in scripts in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Awk Field Extraction Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
1:30remaining
What is the output of this awk command?
Given a file data.txt with the following content:
apple 10 red
banana 5 yellow
cherry 20 red

What is the output of this command?
awk '{print $2}' data.txt
Bash Scripting
awk '{print $2}' data.txt
A
10
5
20
B
apple
banana
cherry
C
red
yellow
red
D
1
2
3
Attempts:
2 left
💡 Hint
Remember, awk fields are numbered starting from 1, and $2 means the second word in each line.
💻 Command Output
intermediate
1:30remaining
Which awk command extracts the third field from a CSV file?
You have a CSV file records.csv with lines like:
John,Doe,30
Jane,Smith,25
Bob,Brown,40

Which command correctly prints the third field (age) from each line?
Aawk -F':' '{print $3}' records.csv
Bawk '{print $3}' records.csv
Cawk -F',' '{print $2}' records.csv
Dawk -F',' '{print $3}' records.csv
Attempts:
2 left
💡 Hint
CSV fields are separated by commas, so set the field separator to a comma.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in this awk script snippet
What is wrong with this awk command?
awk '{print $1 $2}' file.txt

It is intended to print the first and second fields separated by a space.
AMissing comma between $1 and $2 inside print
BNo error, command is correct
CIncorrect use of single quotes
DMissing semicolon after print statement
Attempts:
2 left
💡 Hint
In awk, print $1 $2 prints the fields separated by the output field separator (OFS), which defaults to a single space.
🚀 Application
advanced
2:00remaining
Extract and sum the second field values using awk
Given a file numbers.txt with lines:
a 3
b 7
c 10

Which awk command sums all values in the second field and prints the total?
Aawk '{print sum + $2}' numbers.txt
Bawk '{sum = $2} END {print sum}' numbers.txt
Cawk '{sum += $2} END {print sum}' numbers.txt
Dawk 'END {print sum}' numbers.txt
Attempts:
2 left
💡 Hint
Use a variable to accumulate the sum inside the main block, then print it in the END block.
🔧 Debug
expert
2:30remaining
Why does this awk command fail to extract the fourth field?
You run this command:
awk '{print $4}' file.txt

But it prints empty lines even though the file has data.
The file lines look like:
one,two,three,four,five

What is the most likely reason?
AThe file uses commas as separators but awk expects spaces by default
BThe file uses tabs as separators but awk expects spaces by default
CThe file lines have trailing spaces causing $4 to be empty
DThe file uses multiple spaces or tabs, causing fields to be miscounted
Attempts:
2 left
💡 Hint
Check what character separates fields in the file and if awk is set to use it.