Why is sed replace + redirection deleting my file?

I use sed to find and replace two lines in a file in bash (GNU sed)

This is the file after

-rw-r--r-- 1 websync www-data 4156 mar 27 12:56 /home/websync/tmp/sitio-oficial/sitios/wp-config.php 

here is the command that I run

 sed 's/www-test/www/g' /home/websync/tmp/sitio-oficial/sitios/wp-config.php > /home/websync/tmp/sitio-oficial/sitios/wp-config.php 

and result

 -rw-r--r-- 1 websync www-data 0 mar 27 13:05 /home/websync/tmp/sitio-oficial/sitios/wp-config.php 

EDIT: If I do not redirect the output of sed, then I got the correct output. If I redirect to a new file, everything works fine.

+4
source share
3 answers

This is normal. you cannot read and write to the same file in such a pipeline. (this will crash with utilities other than sed).

Use the in-place -i flag instead:

 sed -i 's/www-test/www/g' /home/websync/tmp/sitio-oficial/sitios/wp-config.php 
+14
source

sed reads your files as a stream and issues a stream. As soon as you redirect to your file, the contents are overwritten, and since this file is read as a stream, it has not even begun to read sed. When sed starts reading a file, it is empty, so it immediately ends without output.

Use -i to do your own editing, instead:

 sed 's/www-test/www/g' -i /home/websync/tmp/sitio-oficial/sitios/wp-config.php 
+4
source

Redirection opens the file for output, trimming it. This happens simultaneously with sed , opening it for reading, so sed sees a truncated version. You should redirect your output to another file to avoid merging the input or use sed in-place edit mode instead of using redirection:

sed 's/www-test/www/g' -i /home/websync/tmp/sitio-oficial/sitios/wp-config.php

+2
source

Source: https://habr.com/ru/post/1403705/


All Articles