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

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.

Answer

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.

Attribution
Source : Link , Question Author : Matt Norris , Answer Author : Dennis Williamson

Leave a Comment