Combining Sed and Grep24 Aug 2022
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
sed to do global matching, and not replace just the first occurrence.
sed can do this work for us:
$ sed -n s/needle//pg haystack.txt something
-n option suppresses output, and the
p command selectively enables it.