0

I want to combine the -o and -v flag of grep. But i do not get any output. I have the file:

foo
bar
foobar

I call: grep -vo foo ./file

What i expect:

bar
bar

or


bar
bar

But i get no output.

From the man page of grep:

   -o, --only-matching
          Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
...
   -v, --invert-match
          Invert the sense of matching, to select non-matching lines.

When i only use one flag, the behavior is as i expect it. But how to make grep work with both flags work at the same time? I use grep (GNU grep) 3.3 on Debian AMD64.

1 Answer 1

1

What you are telling grep is:

  • Print only foo for each line that has it, and
  • Print lines that don't have a foo

What you meant to tell grep was:

  • Print lines that don't match foo, or the parts of lines that don't include a foo

That can be reduced to:

  • Print every line, but remove foo from them

I think sed is the perfect tool to do this:

$ sed 's/foo//g' ./file

bar
bar

This says: for each line, substitute foo with nothing globally. By globally it means every instance in the line.

If you also want to delete empty lines:

$ sed -e 's/foo//g' -e '/^$/d' ./file
bar
bar

This says:

  • substitute foo with nothing globally, then
  • for each empty line, delete it

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .