0
0
Bash Scriptingscripting~20 mins

grep in scripts in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Grep Guru
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of grep with multiple options
What is the output of this bash command when run on a file named data.txt containing the lines:
apple
banana
Apple pie
banana split
APPLE

Command:
grep -i 'apple' data.txt
Bash Scripting
grep -i 'apple' data.txt
Aapple
B
apple
Apple pie
APPLE
banana
banana split
C
Apple pie
APPLE
D
apple
Apple pie
APPLE
Attempts:
2 left
💡 Hint
The -i option makes grep ignore case when matching.
💻 Command Output
intermediate
2:00remaining
Using grep to count matching lines
Given a file log.txt with 10 lines, 3 of which contain the word 'error', what is the output of:
grep -c 'error' log.txt
Bash Scripting
grep -c 'error' log.txt
A3
B
error
error
error
C10
D0
Attempts:
2 left
💡 Hint
The -c option counts matching lines instead of printing them.
🔧 Debug
advanced
2:00remaining
Why does this grep command fail?
Consider this script snippet:
if grep 'pattern' file.txt
then
echo 'Found'
fi

Why might this script not print 'Found' even if 'pattern' is in the file?
Bash Scripting
if grep 'pattern' file.txt
then
echo 'Found'
fi
Agrep outputs matching lines but the if condition checks exit status, so if grep outputs nothing, it returns false
Bgrep returns 0 exit status if it finds matches, so the if condition should print 'Found' if pattern exists
Cgrep command is missing the -q option to suppress output, causing the if to fail
DThe script is missing a semicolon after grep command, causing syntax error
Attempts:
2 left
💡 Hint
Check how grep exit status works in if conditions.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this grep usage
Which option shows the correct syntax to search for lines containing 'test' in file.txt and ignore case?
Agrep -i 'test' file.txt
Bgrep -i test file.txt
Cgrep -i "test file.txt"
Dgrep -i test -file.txt
Attempts:
2 left
💡 Hint
Check how to pass the pattern and filename correctly.
🚀 Application
expert
3:00remaining
Extract lines with numbers and save count
You want to write a bash script that extracts all lines containing digits from input.txt and saves them to numbers.txt. Then, you want to store the count of these lines in a variable count. Which snippet does this correctly?
Acount=$(grep -E '[0-9]' input.txt > numbers.txt | wc -l)
B
grep -E '[0-9]' input.txt > numbers.txt
count=$(wc -l < numbers.txt)
Ccount=$(grep -E '[0-9]' input.txt | tee numbers.txt | wc -l)
D
grep -E '[0-9]' input.txt | wc -l > numbers.txt
count=$(cat numbers.txt)
Attempts:
2 left
💡 Hint
Use a command that both saves output and counts lines in a single pipeline.