Don't truncate when redirecting
A common problem in shell languages is truncating a file that you're trying to transform by redirecting into it.
Let's say I have a file full of "a"'s
PROMPT> cat test.txt
aaaaaa
And I want to switch them all to "b"'s
PROMPT> cat test.txt | tr 'a' 'b'
bbbbbb
But when I try to redirect into the same file I truncate file:
PROMPT> cat test.txt | tr 'a' 'b' > test.txt
PROMPT> cat test.txt
# nothing
This is because the shell truncates "test.txt" for redirection before cat
reads the file.
An alternate approach is to use tee
.
PROMPT> cat test.txt | tr 'a' 'b' | tee test.txt
bbbbbb
PROMPT> cat test.txt
bbbbbb
tee
will write the output to both the file and to standard out, but will do so at the end of the pipe, after the cat
command reads from the file.