LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

sponge

Soak up stdin before writing to file

TLDR

Overwrite file with pipeline output
$ cat [file.txt] | sort | sponge [file.txt]
copy
Filter and save in place
$ grep "[pattern]" [file.txt] | sponge [file.txt]
copy
Transform and overwrite
$ sed 's/old/new/g' [file.txt] | sponge [file.txt]
copy
Append instead of overwrite
$ echo "new line" | sponge -a [file.txt]
copy

SYNOPSIS

sponge [options] file

DESCRIPTION

sponge reads standard input and writes to a file. Unlike shell redirection, it reads all input before opening the output file, allowing safe in-place modifications.The tool is part of moreutils and solves the problem of using a file as both input and output in a pipeline.

PARAMETERS

-a

Append to file instead of overwriting.

EXAMPLES

Without sponge (fails):

$ sort file.txt > file.txt  # Results in empty file!
copy
With sponge (works):
$ sort file.txt | sponge file.txt
copy

INSTALL

sudo apt install moreutils
copy
sudo dnf install moreutils
copy
sudo pacman -S moreutils
copy
sudo apk add moreutils
copy
sudo zypper install moreutils
copy
brew install moreutils
copy
nix profile install nixpkgs#moreutils
copy

CAVEATS

Loads entire input into memory. Very large files may exhaust memory. Part of moreutils package. Creates a temp file internally and renames it atomically when possible. If no file is specified, sponge outputs to stdout.

HISTORY

sponge is part of moreutils, a collection of Unix tools created by Joey Hess. It addresses a common shell scripting pitfall where redirection to the input file truncates it before reading.

SEE ALSO

tee(1), cat(1), moreutils(7)

Braincup
Open source brain training for math, memory and focus
Braincup mini-games
41 mini-games · Apache-2.0
No ads · No tracking
Play in browser
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid
276 stars
From the maker of Linux Command Library
Copied to clipboard
Braincup
Open source brain training for math, memory and focus. 41 mini-games, from mental arithmetic to Sudoku, N-Back and Solo Chess.
Apache-2.0 licensed · No ads · No tracking · No account
From the maker of Linux Command Library
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid