LFCS · Question #838
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 ^# command uses the -v option to invert the match, displaying all lines that do not begin with the pound symbol (#).
Question
Options
- A/bin/grep ^# foobar
- B/bin/grep -v ^# foobar
- C/bin/grep #$ foobar
- D/bin/grep -v #$ foobar
How the community answered
(30 responses)- A3% (1)
- B93% (28)
- D3% (1)
Why each option
The `grep -v ^#` command uses the `-v` option to invert the match, displaying all lines that do not begin with the pound symbol (`#`).
`/bin/grep ^# foobar` would print all lines that *begin* with `#`, which is the opposite of what is requested.
The `/bin/grep -v ^# foobar` command correctly achieves the desired outcome. The `^#` pattern matches lines that begin with a pound symbol, and the `-v` option inverts the match, causing `grep` to print only the lines that *do not* match the pattern (i.e., do not begin with `#`).
`/bin/grep #$ foobar` searches for lines that *end* with `#`, not lines that begin with `#`, and it does not invert the match.
`/bin/grep -v #$ foobar` would print lines that *do not end* with `#`, which is not the requirement of lines not beginning with `#`.
Concept tested: GREP pattern matching and inversion
Source: https://man7.org/linux/man-pages/man1/grep.1.html
Topics
Community Discussion
No community discussion yet for this question.