3 ms·
sponge rules, but you need to be careful. Lets say you wanted to search/replace a file with sed and sponge, then this does not work: cat file.txt | sed "s/a
by OskarS 6y ago
sponge rules, but you need to be careful. Lets say you wanted to search/replace a file with sed and sponge, then this does not work:
cat file.txt | sed "s/a/b/g" | sponge > file.txt
Because bash opens file.txt for writing and truncates it
immediately, so "cat file.txt" wont output anything. You have to do this for it to work:
cat file.txt | sed "s/a/b/g" | sponge file.txt
sponge wont open the file for writing until it's sponged everything up. If you remember this, sponge is an awesome tool in the UNIX toolbox.
- bonoboTP 6y agoOf course with sed you'd use the -i flag.
- jniedrauer 6y agoUnless you're on MacOS, in which case it's -i''. I always have to rewrite cross platform scripts at least once.
- dwheeler 6y agoRight. The sed -i option is incompatible between MacOS & Linux, and it isn't in the POSIX standard. The POSIX folks don't want to add it because it's possible to do work without it, even though no one wants to. Maybe sponge should be in the POSIX standard.
- waynesonfire 6y agoI ran into this on FreeBSD. I do have gnu sed and other gnu utilities installed on my Mac to help me feel more at home.
- knome 6y agoThis doesn't seem to have any real advantage over just using an intermediate file.
- OskarS 6y agoOf course you can always use an intermediate file, the point is that sponge is a very convenient way to just do it in a single command, without having to use intermediate files. You don't have to use pipes either, you know. You can just save the output from every command to an intermediate file, then run the next command with that file as input.