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
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.)