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 > tmp && mv tmp

# Replaces all instances of foo with bar
sed 's/foo/bar/g' > tmp && mv tmp

With sponge this becomes:

expand -t4 | sponge

sed 's/foo/bar/g' | sponge

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.

Back to all posts

implenton is my (Mészáros Róbert) online web development-related presence, playground, and the name of my company of one.