I am learning bash and am not able to understand what is going wrong with the output redirection in the following example:
I have a file called myfile.txt with the following content.
Practice makes Perfect
I am going to use tr
command to replace P with p:
cat myfile.txt | tr P p
This does what I want, now I am going to put the result back into the original file:
cat myfile.txt | tr P p > myfile.txt
But after executing the above command myfile.txt is empty... why is this happening?
Update:
If I send the output to a different file, then it works as expected:
cat myfile.txt | tr P p > anotherfile.txt
cat myfile.txt | tr P p >> myfile.txt
. Appending to a file does not create a new file, and in that case the content is not deleted. Well, it gets repeated withtr P p
altered content. – nobody Aug 22 '19 at 05:33myfile.txt
for writing and truncates it first - see for example Warning regarding ‘>’ – steeldriver Aug 22 '19 at 05:42