In-place processing with grep

Daniel Standage picture Daniel Standage · Oct 20, 2010 · Viewed 18.1k times · Source

I've got a script that calls grep to process a text file. Currently I am doing something like this.

$ grep 'SomeRegEx' myfile.txt > myfile.txt.temp
$ mv myfile.txt.temp myfile.txt

I'm wondering if there is any way to do in-place processing, as in store the results to the same original file without having to create a temporary file and then replace the original with the temp file when processing is done.

Of course I welcome comments as to why this should or should not be done, but I'm mainly interested in whether it can be done. In this example I'm using grep, but I'm interested about Unix tools in general. Thanks!

Answer

Alexey picture Alexey · Jun 27, 2015

sponge (in moreutils package in Debian/Ubuntu) reads input till EOF and writes it into file, so you can grep file and write it back to itself.

Like this:

grep 'pattern' file | sponge file