I am trying to find a way to use awk to print the lines between two patterns, Virtual and Redirect, but only if the two patterns are consecutive, exclusive of any other strings between them.
Example pre-formatted file:
<VirtualHost ${APACHE_IP}: 80>
ServerName domain1.com:
ServerAlias www.domain1.com:
RedirectMatch permanent "^(.*)$" https: //www.otherdomain.com/
<VirtualHost ${APACHE_IP}: 80>
ServerName dev1-www-domain3.domain.com:
<VirtualHost ${APACHE}: 80>
ServerName domain3.com:
RedirectPermanent / https: //www.domain3.com/
<VirtualHost ${APACHE_IP}: 80>
ServerName www.domain4.com:
<VirtualHost 10.0.0.1: 80>
ServerName web1.domain.com:
RedirectPermanent / https: //web1.domain.com/
<VirtualHost 10.0.0.1: 80>
ServerName web1.www_site_com.domain.com:
<VirtualHost 10.0.0.1: 80>
ServerName web1.dev_site_com.domain.com:
<VirtualHost 10.0.0.1: 443>
ServerName web1.domain.com
I need to get all the domains that correspond to a redirect. So the output should be (whether the output includes the Virtual or Redirect lines is irrelevant to me as I can always grep them out, but I do not need them):
ServerName domain1.com:
ServerAlias www.domain1.com:
ServerName domain3.com:
ServerName web1.domain.com:
I have been trying a number of different methods, and the last one I tried was this:
awk 'f { if (/Redirect/) {
printf "%s", buf; f = 0; buf = ""
} else buf = buf $0 ORS
}
/Virtual/ { f = 1}' file
But it will start at the first instance of 'Virtual' and continue grabbing lines until it gets to a 'Redirect', regardless of any other 'Virtual' strings in between. I only want it to return strings between a matched set of 'Virtual' and 'Redirect' and ignore any blocks that are between two 'Virtual' strings.
This is what the output ends up as:
ServerName domain1.com:
ServerAlias www.domain1.com:
ServerName dev1-www-domain3.domain.com:
<VirtualHost ${APACHE}: 80>
ServerName domain3.com:
ServerName www.domain4.com:
<VirtualHost 10.0.0.1: 80>
ServerName web1.domain.com:
All other examples I have been finding are decidedly not my particular use case, as close as they might be. I have spent several hours looking through Stackexchange/overflow and Reddit with no luck so far.
Virtual” and “Redirect”.) (2) I was going to say that “but only if the two patterns are consecutive, exclusive of any other strings between them” was also unclear, but I see that you eventually got around to explaining it. (3) “ServerName web1.domain.com” appears twice in your input data. This is confusing.ServerName web1.domain.comdoes in fact appear twice in the file, which is why I included it. This file is an amalgamation of several Apache conf files because I need to combine them all and isolate redirected domains regardless if they appear in more than one conf and may not be redirected in all confs.