为什么sed replace + redirection会删除我的文件?

jpe*_*lli 4 bash sed io-redirection

我正在使用sed搜索并替换bash文件中的两个字符串(GNU sed)

这是之后的文件

-rw-r--r-- 1 websync www-data 4156 mar 27 12:56 /home/websync/tmp/sitio-oficial/sitios/wp-config.php
Run Code Online (Sandbox Code Playgroud)

这是我运行的命令

sed 's/www-test/www/g' /home/websync/tmp/sitio-oficial/sitios/wp-config.php > /home/websync/tmp/sitio-oficial/sitios/wp-config.php
Run Code Online (Sandbox Code Playgroud)

结果

-rw-r--r-- 1 websync www-data 0 mar 27 13:05 /home/websync/tmp/sitio-oficial/sitios/wp-config.php
Run Code Online (Sandbox Code Playgroud)

编辑:如果我没有重定向sed的输出,那么我得到了正确的输出.如果我重定向到一个新文件,一切正常.

bri*_*ice 15

这个是正常的.你不能在像这样的管道中读取和写入同一个文件.(这将与sed之外的其他实用程序失败).

-i改为使用就地标志:

sed -i 's/www-test/www/g' /home/websync/tmp/sitio-oficial/sitios/wp-config.php
Run Code Online (Sandbox Code Playgroud)


Pau*_*aul 5

sed 将文件作为流读取并输出流。一旦执行到文件的重定向,内容就会被覆盖,并且由于该文件正在作为流读取,因此 sed 甚至还没有开始读取它。当 sed 开始读取文件时,它是空的,因此它立即完成且没有输出。

使用-i, 进行就地编辑:

sed 's/www-test/www/g' -i /home/websync/tmp/sitio-oficial/sitios/wp-config.php
Run Code Online (Sandbox Code Playgroud)