nerdexam
CompTIA

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.

GNU and Unix Commands

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)
  • A
    7% (3)
  • B
    89% (40)
  • C
    2% (1)
  • D
    2% (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.

A/bin/grep ^# foobar

Without -v, this prints lines that DO begin with #, the opposite of what is required.

B/bin/grep -v ^# foobarCorrect

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.

C/bin/grep #$ foobar

The pattern #$ matches lines that END with #, not lines that begin with it, and there is no inversion.

D/bin/grep -v #$ foobar

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

#grep#invert match#regex anchors#text filtering

Community Discussion

No community discussion yet for this question.

Full LX0-103 Practice