Unix tools: sponge

Joey writes about the lack of new tools that fit into the Unix philosophy. My favourite of such things I’ve written is sponge. It addresses the problem of editing files in-place with Unix tools, namely that if you just redirect output to the file you’re trying to edit then the redirection takes effect (clobbering the contents of the file) before the first command in the pipeline gets round to reading from the file. Switches like sed -i and perl -i work around this, but not every command you might want to use in a pipeline has such an option, and you can’t use that approach with multiple-command pipelines anyway.

I normally use sponge a bit like this:

sed '...' file | grep '...' | sponge file

Since it’s so trivial I imagine lots of other people have written something similar (another common name for it seems to be inplace; my name indicates soaking up all the input and then squeezing it all out again); but I do keep meaning to try to get a rewritten version into coreutils at some point.