Skip to main content
3 of 3
added 13 characters in body
Stewart
  • 16.1k
  • 5
  • 49
  • 101

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
Stewart
  • 16.1k
  • 5
  • 49
  • 101