Bash – Permission Denied when using Sed

bashpermissionssed

I am using Sed to find and replace a string in a file. This is the first time working with it so I maybe doing it wrong,

I have a file thats owned by "root" called "test.properties" and I want to replace "world" with "cat".

So I run this command:

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

And it works great, but when I want to write to the SAME file like this:

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

It says "-bash: test.properties: Permission denied", but I am using "sudo" so why is it denied?

Best Answer

Do not run the command you are trying to run

If you try to redirect output from sed back into the same file it will blank it out, deleting all of the files contents. Try something like this:

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

You get permission denied because the redirection part of the command is not run via sudo, but run as your normal user.

The first command works because you are simply reading the first file and writing to a file you own, so you regular user could do that.

Related Topic