I want to delete a block of specific server from this file
NameVirtualHost *
<VirtualHost *>
DocumentRoot "/Applications/MAMP/htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *>
DocumentRoot "/Applications/MAMP/htdocs/bedrock/web"
ServerName bedrock
</VirtualHost>
<VirtualHost *>
DocumentRoot "documentroot"
ServerName newserver
</VirtualHost>
So far I've used the following, but it doesn't seem to give me the proper result, but instead greps for each line of the block (of the inner grep) individually.
grep -vF "$(grep -w -B 2 -A 1 'newserver'/Applications/MAMP/conf/apache/httpd.conf)" /Applications/MAMP/conf/apache/httpd.conf;
The above results in the following:
NameVirtualHost *
DocumentRoot "/Applications/MAMP/htdocs"
ServerName localhost
DocumentRoot "/Applications/MAMP/htdocs/bedrock/web"
ServerName bedrock
While instead I want the following:
NameVirtualHost *
<VirtualHost *>
DocumentRoot "/Applications/MAMP/htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *>
DocumentRoot "/Applications/MAMP/htdocs/bedrock/web"
ServerName bedrock
</VirtualHost>
Another one with
diff
and parts of your initial command:If you want to delete an entry with ServerName newserver then use this perl one-liner:
Using a variable:
RegEx Demo
Explanation:
This perl command uses a regex that matches a block starting from these 2 tags:
and
and finds this pattern in between these 2 patterns:
It uses a negative lookahead pattern using
(?!</VirtualHost>)
that makes sure only whenServerName
test comes then only match is found.This is a 'trick' to remove the last Vhost by the known numbers of lines it contains
awk alone:
RS
defines</VirtualHost>
as record separator andawk
will prints those records($0
) that doesn't match withServerName newserver
in it. And then print theRS
(</VirtualHost>
) again which is removed when we change RS to that.