Home > Software design >  Cut Apache virtual host block
Cut Apache virtual host block

Time:12-13

I'm trying to cut certain virtual host from file which has a lot of them using bash.

Eg. in my script I would like to get virtual host which uses the_one_known2.example.com, but another time the_one_known3.example.com, namely I would like to get some part form apache config file with beforehand known URL (present in ServerName or ServerAlias) which is set in bash script as a parameter.

<VirtualHost *:80 *:${SERVER_PORT}>
    ServerName      test1.example.com
    ServerAlias     test2.example.com
    ServerAlias     the_one_known1.example.com
    ServerAlias     test3.example.com
</VirtualHost>
<VirtualHost *:80 *:${SERVER_PORT}>
    ServerName      test4.example.com
    ServerAlias     the_one_known2.example.com
    ServerAlias     test5.example.com
    ServerAlias     test6.example.com
</VirtualHost>
<VirtualHost *:80 *:${SERVER_PORT}>
    ServerName      the_one_known3.example.com
    ServerAlias     test7.example.com
    ServerAlias     test8.example.com
    ServerAlias     test9.example.com
</VirtualHost>

So I my URL variable would change to eg. the_one_known2.example.com I would get:

<VirtualHost *:80 *:${SERVER_PORT}>
    ServerName      test4.example.com
    ServerAlias     the_one_known2.example.com
    ServerAlias     test5.example.com
    ServerAlias     test6.example.com
</VirtualHost>

[EDIT] So far I tried to find first line of a selected virtual host:

url_line=$(grep -n -m 1 "${URL}" ./apache.conf" | sed  's/\([0-9]*\).*/\1/')
vitual_host_start_line="$((app_line-1))" // this is an assumption that Virtual Host starts just one line before the first occurance of URL
echo $vitual_host_line // the place it starts

But I have a problem to find a last line of this virtual host because it is first occurence of </VirtualHost> after vitual_host_start_line

CodePudding user response:

With awk:

awk -v name="the_one_known2.example.com" 'BEGIN{RS=ORS="</VirtualHost>\n"} $0~name{print; exit}' file

I assume the_one_known2.example.com is no substring of another domain in your file.

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

CodePudding user response:

With your shown samples, please try following awk code. Written and tested in GNU awk.

awk -v RS='<VirtualHost[^/]*/' -v ORS="VirtualHost>\n" 'RT~/[[:space:]] the_one_known2\.example\.com\n/{print RT}' Input_file

Explanation: Simple explanation would be, making RS(record separator) from <VirtualHost till next / occurrence(non-greedy match). Then checking if it has [[:space:]] the_one_known2\.example\.com\n if yes then print matched value, this will print VirtualHost> at ending of passage since its set as ORS value in program.

  • Related