010-100 · Question #2
Which of the following commands will output all of the lines with the name Fred in upper or lower case but not the word red from the file data_file? (Select TWO correct answers)
The correct answer is D. grep '[Ff]red' data_file E. grep -i fred data_file. To match lines containing Fred in any case while excluding lines containing only red, the grep pattern must require the letter f before red, achieved via a character class or the -i flag.
Question
Which of the following commands will output all of the lines with the name Fred in upper or lower case but not the word red from the file data_file? (Select TWO correct answers)
Options
- Agrep -v fred data_file
- Bgrep '[f]red' data_file
- Cegrep fred data_file
- Dgrep '[Ff]red' data_file
- Egrep -i fred data_file
How the community answered
(43 responses)- A2% (1)
- B12% (5)
- C5% (2)
- D81% (35)
Why each option
To match lines containing Fred in any case while excluding lines containing only red, the grep pattern must require the letter f before red, achieved via a character class or the -i flag.
grep -v fred inverts the match and outputs lines that do NOT contain 'fred', which is the opposite of the desired behavior.
grep '[f]red' is equivalent to grep fred and only matches lowercase 'fred', missing uppercase 'Fred'.
egrep fred performs a case-sensitive search and only matches lowercase 'fred', missing uppercase 'Fred'.
grep '[Ff]red' uses a character class to match either 'Fred' or 'fred', and because the pattern requires the letter f, lines containing only 'red' are not matched.
grep -i fred performs a case-insensitive search for the full pattern 'fred', which matches 'Fred' and 'fred' but not 'red' since the f must be present in the matched text.
Concept tested: grep case-insensitive pattern matching with character classes
Source: https://man7.org/linux/man-pages/man1/grep.1.html
Topics
Community Discussion
No community discussion yet for this question.