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?

  • You're getting permission denied because your shell doesn't have the right to redirect its output to the file (output redirection when using sudo isn't straightforward... The only thing that runs with elevated privileges is "sed s/world/cat/", your current shell takes care of the output.) The answer provided by @Pratik below is right though, you're using sed all wrong. – Tzarium May 12 '11 at 23:01
  • well not quite all wrong, my initial command works fine, then I just have to move it back :) – Doug Molineux May 12 '11 at 23:11
  • 1
    Well, true :) To achieve what you wanted from the beginning, you could always do something like "sed s/world/cat/ <test.properties | sudo tee test.properties" – Tzarium May 13 '11 at 7:14

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.

  • Oh wow, thanks! I didn't know that :) – Doug Molineux May 12 '11 at 23:00
  • 3
    Some versions of sed have the -i "edit files in place" option. Also I don't understand why you are piping the output of the sed command to mv and the mv won't be executed as root so it should still fail. – Mark Wagner May 13 '11 at 0:09
  • @embobo - When you say "some versions of sed" if I put this inside a bash script can I be fairly confident that it will run on "Most versions" of Linux? Ubuntu is probably the most important for this test case – Doug Molineux May 16 '11 at 19:25
  • Yes, you should be good with Ubuntu. You could look at the man page to verify. – Mark Wagner May 16 '11 at 20:25
sudo sed -i s/world/cat/ test.properties

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.