Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add missing ServerName to httpd.conf file using sed

Tags:

linux

sed

I have the following virtual hosts in httpd.conf file

    <VirtualHost *:80>
    ## could be comments
    could be any line
    could be any line
    could be any line
    </VirtualHost>

    <VirtualHost *:80>
       could be any line
    ## could be comments
    could be any line
    could be any line
    could be any line
    could be any line
    could be any line
    </VirtualHost>

    <VirtualHost *:80>
## may have comments
    ServerName ppp.com
        could be any line
    could be any line
    could be any line
  </VirtualHost>

    <VirtualHost *:443>
   ## could be empty
    ServerName zzz.com
    could be any line
    could be any line
    could be any line
    </VirtualHost>

I'm trying to add "ServerName abc.com" to every virtual host which doesn't have a ServerName already setup.

I was trying to do it in sed, and I'm not getting anywhere .. any help ?

This is what I have so far ...

sed '/^[ \t]*<VirtualHost/,/^[ \t]*<\/VirtualHost/{
/^ServerName/!{
   /<VirtualHost/{
     /^/a\ServerName abc.com

   }
  }
}' httpd.conf
like image 660
user2045331 Avatar asked Jan 30 '26 04:01

user2045331


1 Answers

Using sed:

sed '/<VirtualHost/{
       :a N;/<\/VirtualHost>/!b a;
       /ServerName/!s!\(</VirtualHost>\)!ServerName abc.com\n\1!
}' input

I don't think awk has any advantages over sed for this particular problem.

like image 71
perreal Avatar answered Feb 01 '26 21:02

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!