I'm writing a command to prepend some text to a bunch of files which match a certain pattern:
for file in $(find . -name "*.txt"); do sed "1s/^/hello/" $file; done
If I write to stdout
or a different file (e.g. "$file.bak"
), everything works according to plan, but when I try to have the command write back to the same file, the content of the files gets wiped out:
for file in $(find . -name "*.txt");do sed "1s/^/hello/" $file > $file; done
I find the behavior surprising, could someone explain why this happens, conceptually? I'm on macOS and I've tried this in bash
and zsh
to the same effect.
(Note that I'm aware of sed -i ""
for in-place writing, but I'd like to pipe the result to a different command before writing in-place.)
tee
utility, which I'm learning about now, seems to allow me to write back to the original file. – Dan Jun 09 '20 at 15:42tee
is a viable alternative tosponge
. – Dan Jun 09 '20 at 15:53