Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm attempting to write a script that uses sed to copy the default file for apache and writes a new file, replacing /var/www ($DOC_ROOT below) with my own directory, $NEW_SITES_DIR. However, sed isn't operating correctly running under sudo: I get a "permission denied" error for the following:

sudo sed -ie 's:$DOC_ROOT:$NEW_SITES_DIR:g' < default > $NEW_SITE

I've tried to spawn a sub-shell

sudo sh -c "sed -ie 's:$DOC_ROOT:$NEW_SITES_DIR:g' < default > $NEW_SITE"

and use tee

sudo sed -ie 's:$DOC_ROOT:$NEW_SITES_DIR:g' < default | sudo tee $NEW_SITE

but I get a "no input files" error instead.

I'm sure the last two attempts I have written are a bit off. Any suggestions would be greatly appreciated.


Thank you to everyone for your help. Here is the exact command:

sudo sed -e "s:$DEF_SITES_DIR:$NEW_SITES_DIR:g" < $DEF_SITE | sudo tee $NEW_SITE

And here is a key phrase from this reference:

Don’t lose sleep over this, but someday it will come handy, and when you can figure out why the “sudo” does not apply after the “>” in your command, remember tee and come back here.

share|improve this question
up vote 3 down vote accepted

Your problem is the -i. That's telling sed to edit the file in place, but you're providing the file on stdin by redirecting it. Try dropping the -i.

There's really no need to redirect the input file since sed accepts a filename as an argument. If the read permissions on the file are restricted then sudo sed (and not using redirection) will take care of that. By not using -i the original file will be left intact.

The sudo tee should take care of the write permissions for output if that's necessary.

share|improve this answer
sudo tee was definitely the way to go. I've updated my question with the exact solution. – Matt Norris Nov 7 '10 at 23:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .