使用 Sed 时权限被拒绝

使用 Sed 时权限被拒绝

我正在使用 Sed 查找并替换文件中的字符串。这是我第一次使用它,所以我可能做错了,

我有一个名为“test.properties”的文件,其所有者为“root”,我想用“cat”替换“world”。

因此我运行这个命令:

sudo sed s/world/cat/ <test.properties >newtest.properties

而且它运行得很好,但是当我想像这样写入同一个文件时:

sudo sed s/world/cat/ <test.properties >test.properties

它说“-bash:test.properties:权限被拒绝”,但我正在使用“sudo”,那么为什么它被拒绝呢?

答案1

不要运行您尝试运行的命令

如果您尝试将 sed 的输出重定向回同一个文件,它将清空该文件,删除该文件的所有内容。请尝试以下操作:

sed s/world/cat/ <test.properties >newtest.properties && sudo mv newtest.properties test.properties

您被拒绝权限,因为命令的重定向部分不是通过 sudo 运行,而是以普通用户身份运行。

第一个命令有效,因为您只是读取第一个文件并写入您拥有的文件,所以普通用户可以这样做。

答案2

sudo sed -i s/world/cat/ test.properties

相关内容