For example, here's my command I'm using:
tr -d '\n' < newfile.ppm
I want to output the results to that exact same file, so I am now doing:
tr -d '\n' < newfile.ppm > newfile.ppm
Why is this not working and how can I get it to work?
For example, here's my command I'm using:
tr -d '\n' < newfile.ppm
I want to output the results to that exact same file, so I am now doing:
tr -d '\n' < newfile.ppm > newfile.ppm
Why is this not working and how can I get it to work?
This is an extremely common "gotcha".
When you redirect stdout or stderr to write to a file, the shell will first truncate the file to prepare it for writing. So what's occurring is roughly the following:
newfile.ppm
newfile.ppm
to length 0newfile.ppm
tr -d '\n'
. As you can see, at this point, the contents of newfile.ppm
are already gone, so there is nothing to read.To work around this, just output to another file instead. You can then rename it afterwards
This'll do the job you want.
[stephan@stephan] ~
$ echo "meh
" > file
[stephan@stephan] ~
$ cat file | tr -d '\n' > file ; cat file
meh
cat file | tr -d '\n' > newfile ; mv newfile file
– Stephan Sep 30 '16 at 00:45