Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why sed replace + redirection deletes my file?

I am using sed to search and replace two strings 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 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 the 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 don't redirect sed's output, then I got the correct output. If I redirect to a new file, all works ok.

like image 498
jperelli Avatar asked Mar 27 '12 16:03

jperelli


3 Answers

This is normal. you can't read and write to the same file in a pipeline like this. (this will fail with other utilities than sed).

Use the in-place flag -i instead:

sed -i 's/www-test/www/g' /home/websync/tmp/sitio-oficial/sitios/wp-config.php
like image 193
brice Avatar answered Oct 18 '22 03:10

brice


sed reads your files in as a stream and outputs a stream as well. As soon as you perform the redirection into your file the contents are overwritten, and since that file is being read as a stream, it hasn't even started being read by sed yet. When sed does start reading the file it is empty so it finishes immediately with no output.

Use -i, to do an in-place edit, instead:

sed 's/www-test/www/g' -i /home/websync/tmp/sitio-oficial/sitios/wp-config.php
like image 31
Paul Avatar answered Oct 18 '22 02:10

Paul


The redirection opens the file for output, truncating it. This happens simultaneously to sed opening it for reading, so sed sees the truncated version. You should redirect your output to a different file to avoid clobbering your input, or use sed's in-place editing mode instead of using redirection:

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

like image 2
moonshadow Avatar answered Oct 18 '22 03:10

moonshadow