How can I use sed in /etc/apache2/sites-available?

4

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.


ANSWERED

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.

Matt Norris

Posted 2010-11-07T02:37:07.683

Reputation: 439

Answers

3

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.

Paused until further notice.

Posted 2010-11-07T02:37:07.683

Reputation: 86 075

sudo tee was definitely the way to go. I've updated my question with the exact solution. – Matt Norris – 2010-11-07T23:46:41.900