Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help in sed with using a template to create new files for virtual hosts

for j in `cat server_name_list`; do sed -i 's/DIR/${j}/g' dlist1 > $j.conf; done

Basically I am trying to create a number of apache virtual hosts using one virtual host file as a template….

so, template file:
cat /tmp/dlist1

Allow From All
DocumentRoot /var/www/html/DIR
ServerName DIR.com
ServerAlias www.DIR.com
DirectoryIndex index.html index.htm
ErrorLog "logs/DIR_com_error_log"
CustomLog "logs/DIR_com_access_log" common

And the list of servers is in a file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cat /tmp/server_name_list
abc.com
xyz.com
utv.com

so the sed script has to give me three files as in abc.conf, xyz.conf, utv.conf

with this content(just writing the one for "abc" here):

Allow From All
DocumentRoot /var/www/html/abc
ServerName abc.com
ServerAlias www.abc.com
DirectoryIndex index.html index.htm
ErrorLog "logs/abc_com_error_log"
CustomLog "logs/abc_com_access_log" common

>Solution :

Here you go:

for j in `cat server_name_list`; do
  j="${j%.*}"
  sed "s/DIR/$j/g" dlist1 > $j.conf;
done

Explanation:

  • j="${j%.*} uses parameter expansion to remove the .com extension from the server name. The syntax ${j%.*} means to remove the shortest match of .* (i.e., ".com") from the end of the string j.
  • sed "s/DIR/$j/g" dlist1 > $j.conf replaces all occurrences of the string DIR in the dlist1 template file with the current server name j
  • The output of the sed command is redirected to a file with the name $j.conf.

Hope this helps 👍

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading