LX0-103 · Question #25
Which of the following commands will print to standard out only the lines that do not begin with # (pound symbol) in the file foobar?
The correct answer is B. /bin/grep -v ^# foobar. The grep -v flag inverts matching, printing only lines that do NOT match the given pattern. The anchor ^ restricts the pattern to the start of a line.
Question
Which of the following commands will print to standard out only the lines that do not begin with # (pound symbol) in the file foobar?
Options
- A/bin/grep ^# foobar
- B/bin/grep -v ^# foobar
- C/bin/grep #$ foobar
- D/bin/grep -v #$ foobar
How the community answered
(45 responses)- A7% (3)
- B89% (40)
- C2% (1)
- D2% (1)
Why each option
The grep -v flag inverts matching, printing only lines that do NOT match the given pattern. The anchor ^ restricts the pattern to the start of a line.
Without -v, this prints lines that DO begin with #, the opposite of what is required.
The -v flag tells grep to invert its output, printing only lines that do not match the pattern. The pattern ^# anchors to the beginning of the line, so together -v ^# outputs every line that does not start with a pound sign, which is exactly the desired behavior.
The pattern #$ matches lines that END with #, not lines that begin with it, and there is no inversion.
The pattern #$ matches lines ending with #, not lines beginning with it, so even with -v the result is inverted end-of-line matching, not start-of-line.
Concept tested: grep inverted matching with line-start anchor
Source: https://www.gnu.org/software/grep/manual/grep.html
Topics
Community Discussion
No community discussion yet for this question.