0

I have several vhosts in one file that I am looking to break each into a file of their own corresponding to the ServerName. I'm looking to take this file

<VirtualHost *:80>
  ServerName host1.example.com
</VirtualHost>

<VirtualHost *:80>
  ServerName host2.example.com
</VirtualHost>

<VirtualHost *:80>
  ServerName hostN.example.com
</VirtualHost>

to subfiles host1.example.com ... hostN.example.com.

I looked at this question-answer, which is closest to what I'm looking for, but I'm unsure on how to match two lines. It tried a nested if statement,

gawk '{
  if(match($0, /(\<VirtualHost \*:80\>)/, v)){
    if(match($0, /  ServerName (.*)/, s)){
      name=s[1]
      {print name}

    }}}
' samplevhost

and

gawk '{
  if(match($0, /(\<VirtualHost \*:80\>)(\n  )(ServerName)(.*)/, k)){
      name=k[1]
      {print name}

    }}
' samplevhost

to print to screen, but I don't get any output. What am I missing?

1
  • 1
    You're probably missing the fact that you're only matching one line at a time, if nothing else. Try setting a state variable to indicate whether you are inside a <VirtualHost> container or not, then check that state variable to determine whether to do any further processing (e.g. to look for a ServerName directive). Remember that there's no syntax guarantee that ServerName comes first in the VirtualHost container.
    – user
    Aug 5, 2013 at 17:48

1 Answer 1

1

If you're sure that vhost definitions are separated by an empty line, you can make use of Perl's "paragraph mode" slurp which segments its input file into chunks of lines separated by one or more empty lines and processes the file chunk-by-chunk rather than line by line (which is probably what's causing your gawk script to fail). Use -n00 (see perlrun(1)) to process the file "paragraph-by-paragraph":

perl -n00 -e '
    /ServerName\s+(.*)/;
    $file = $1;
    open $fh,">",$file or die "Failed to open file $file for writing: $!\n";
    print $fh $_;
    close $fh' your_file_here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.