-2

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?

JobHunter69
  • 940
  • 5
  • 12
  • 22

2 Answers2

0

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:

  1. Your shell sets stdin to newfile.ppm
  2. Your shell truncates newfile.ppm to length 0
  3. Your shell sets stdout to newfile.ppm
  4. Your shell runs 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

gardenhead
  • 2,017
-1

This'll do the job you want.

[stephan@stephan] ~ 
$ echo "meh                                    
" > file
[stephan@stephan] ~ 
$ cat file | tr -d '\n' > file ; cat file 
meh
Stephan
  • 2,911
  • I just tried it, but doing so results in the whole file being erased – JobHunter69 Sep 30 '16 at 00:42
  • I tweaked what I wrote to match your question more closely. – Stephan Sep 30 '16 at 00:43
  • Here is the command I had inputted: cat newfile.ppm | tr -d '\n' > newfile.ppm – JobHunter69 Sep 30 '16 at 00:43
  • Not sure what's different on your system, this would definitely work though: cat file | tr -d '\n' > newfile ; mv newfile file – Stephan Sep 30 '16 at 00:45
  • 1
    Additionally, this post explains in much greater detail about why your initial approach doesn't work: http://unix.stackexchange.com/questions/159513/what-are-the-shells-control-and-redirection-operators – Stephan Sep 30 '16 at 00:47
  • That link is useful, but when I tried this: tr -d '\n' < newfile.ppm >| bignewfile.txt it works – JobHunter69 Sep 30 '16 at 00:52
  • tr -d '\n' < newfile.ppm >| newfile.ppm however doesn't work. Do you know why? – JobHunter69 Sep 30 '16 at 00:52
  • Scroll down the link I posted, under "Warning regarding '>'" - Redirection of output causes the file … to be opened for writing …. If the file does not exist it is created; if it does exist it is truncated to zero size. – Stephan Sep 30 '16 at 01:00