Sponge, to soak up standard input and write to a file

I came across sponge today, a handy tool with great naming. This is from the man page:

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constricting pipelines that read from and write to the same file.

The problem that solves is not really an issue, but more an inconvenience. With many CLI text manipulation tools, there's no way to change and overwrite the file in one go. We need an intermediary file.

Take, for example, these two commands:

# Converts tabs to four spaces
expand -t4 file.md > tmp && mv tmp file.md
 
# Replaces all instances of foo with bar
sed 's/foo/bar/g' file.md > tmp && mv tmp file.md

With sponge this becomes:

expand -t4 file.md | sponge file.md
 
sed 's/foo/bar/g' file.md | sponge file.md

It's part of the moreutils package, so most likely you have to install it. On Ubuntu you would do this with:

sudo apt install moreutils

The package contains other utilities that I did not explore yet, but they look useful too.