Combining Sed and Grep

tags: shell

The Unix command sed(1) is a lot more powerful than we give it credit for. One of my typical use cases for it is combining it with grep to find something in a text file, like this:

$ cat haystack.txt
hay
hay
something needle
hay
$ grep needle haystack.txt | sed 's/needle//g'
something

This will find any needle in the haystack, and remove it, leaving the rest of the line (in this case, something ). The final g tells sed to do global matching, and not replace just the first occurrence.

However, sed can do this work for us:

$ sed -n s/needle//pg haystack.txt
something

Where the -n option suppresses output, and the p command selectively enables it.