3 ms·
> Why not use > file? This, I learned the hard way, and I am not the only one. So in order for you not to make that mistake: the first thing that happens is th
by GuB-42 6y ago
> Why not use > file?
This, I learned the hard way, and I am not the only one. So in order for you not to make that mistake: the first thing that happens is that "file" is truncated, that happens before any command is run, so
sed s/foo/bar/ file > file
will always result in an empty "file", because it will be truncated before "sed" is run. I lost a couple of hours of work like that, once, and then I learned.
From the manpage of sponge
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.
So, the command
sed s/foo/bar/ file | sponge file
will do what you expect
- atsaloli 6y agoTry sed s/foo/bar/ -i file to edit file.
- GuB-42 6y agoThat what I do now, one thing to note though is that the "-i" option is not always available. Usually, now, it is, but we still have a couple of Solaris servers at work that don't support it. This, btw, is why I hate shell scripts. There are so many variants of bourne shells and UNIX tools that writing a portable script is a minefield, as if properly dealing with spaces wasn't tricky enough...
- atsaloli 6y agoRight you are. The -i option is not standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html https://pubs.opengroup.org/onlinepubs/9699919799/utilities/s...)