0

Currently doing a little experiment in the shell.

My commands are the following :

echo 'This a cool butterfly' > test
sed 's/butterfly/parrot/g' test > test

But then when I am doing a simple cat on my test file, the file is empty. Why?

devconnected
  • 77
  • 1
  • 6

1 Answers1

0

You can't read and write to a file at the same time. In resume, sed is reading your file 'test', but you are writing to this file in the same time, so the result is a empty file.

Try this:

sed -i 's/butterfly/parrot/g' test 

With this the file will be edited in place.

  • The command worked, thanks. But how are my instructions executed 'at the same time'. Doesn't my command mean : take the result of the sed operation and write it (after) to the file? In this case, doesn't it work as a sort of pipe? – devconnected Jan 22 '19 at 20:02
  • No your command means read file test and at the same time we write to it. But before sed can start reading the file, ">" just deleted the contents to start writing data to the start of the file. So at the other hand sed started to read the file already all blank, and ">" end writing the contents as blank, as sed does not find anything anymore, and that is rewrite to the file. ">" starts writing data from the beginning. You can test that running a long time script and directing its output to a file, you can watch the file growing! " – Luciano Andress Martini Jan 23 '19 at 18:24