I want to replace a string with sed and save changes to same file which needs sudo as its a root owned file.

But while doing that I am getting below error

raja@raja-UbuntuVM:~$ sudo sed 's|gateway| |g' /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
iface eth1 inet static

-bash: syntax error near unexpected token `newline'
raja@raja-UbuntuVM:~$ sudo sed 's|gateway| |g' /etc/network/interfaces > /etc/network/interfaces
-bash: /etc/network/interfaces: Permission denied
sudo sed 's|gateway| |g' /etc/network/interfaces > /etc/network/interfaces

That fails because your current (non-sudo) shell attempts to open the interfaces file before sudo is executing. To work around this, use the -i (inplace edit) option of sed:

sudo sed -i 's|gateway| |g' /etc/network/interfaces

edits and replaces the file at the same time.

  • 2
    Worse, even if the perms allowed you to > /etc/network/interfaces, it would have erased the contents of the file because the shell redirection happens before the sed command is run...sed would have an empty input file and produce an empty output file. That's why you have to use -i for in place edits, or a tmpfile if your version of sed doesn't support -i.
    – cas
    Nov 14 '15 at 5:46
  • 1
    Another thing worth noting is that the sudo applies to the command (sed) but not to the redirection. The redirection is happening in your shell, which is running as you (and you don't have permission to overwrite that file). Which is a good thing in this case, otherwise you would have wiped /etc/network/interfaces
    – cas
    Nov 14 '15 at 5:51
  • Both cas and Robert Thank you for clear explanation .
    – rɑːdʒɑ
    Nov 14 '15 at 5:57
  • The comment by cas above is crucial—never use a redirect to try to edit a file in place—but for a case where you want to run a bunch of arbitrary commands in a pipeline and pipe the result to a privileged file, the command tee is worth knowing. pipeline_of_commands | sudo tee privileged_file
    – Wildcard
    Nov 14 '15 at 6:37
  • And for editing a file in place with arbitrary commands (which unlike sed may not have a flag for it), the best answer I've seen is serverfault.com/a/547331/313521
    – Wildcard
    Nov 14 '15 at 6:38

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.