in reply to Parsing file and removing a section

Hi brendonc

The script below shows one way to parse a file when looking for blocks to modify or excize. It splits the file data into an alternating sequence of block separators and block internals, using the regex that matches both separators. Then it scans the sequence backwards, looking for triplets where block-start, block-internals and block-end match your criteria and it splices out the triplet(s).

Since I don't have a httpd.conf, I made up data from your posting. As is, the script below removes the block containing ServerNameTwo.

Be warned that this use of split might be considered scary.<br

HTH
Rudif
#! perl -w use strict; $/ = undef; my $data = <DATA>; my @fields = split /(?<=\n)(<\/?VirtualHost.*>[ \t]*\n)/, $data; printf "sanity check before: %d fields\n", scalar @fields; for (my $i = $#fields-2; $i >= 0; --$i) { if ($fields[$i] =~ m(<VirtualHost.*>[ \t]*\n) && $fields[$i+1] =~ m(ServerNameTwo) && $fields[$i+2] =~ m(<\/VirtualHost>[ \t]*\n) ) { splice @fields, $i, 3; } } printf "sanity check after: %d fields\n", scalar @fields; print join '', @fields; __END__ ### mock httpd.conf file used as test data ### Hello everyone, This is my first post. I've been search through previous posts and several Perl books but I haven't been able to find a solution to my problem. I'm quite new to Perl by the way. Here's the problem. I need to parse a httpd.conf file and remove a VirtualHost block. It looks like this: <VirtualHost 123.123.123.123> ServerNameOne www.domain.com ... </VirtualHost> I need to be able to parse the file, find the appropriate ServerName, and then remove that entire VHost block. I'm stuck on this one. If anyone can help I would greatly appreciate i +t. Thanks, Brendon <VirtualHost 123.123.123.123> ServerNameTwo www.domain.com ... </VirtualHost> qwertzuiop... <SomeOtherBlock> qwertzuiop... </SomeOtherBlock> <VirtualHost 123.123.123.123> ServerNameThree www.domain.com ... </VirtualHost> qwertzuiop... qwertzuiop... qwertzuiop...

Replies are listed 'Best First'.
Re^2: Parsing file and removing a section
by Anonymous Monk on Aug 09, 2016 at 06:49 UTC
    Hi if need to remove multiple domains from a different text file and change
    $fields[$i+1] =~ m(ServerNameTwo)
    into
    $fields[$i+1] =~ m($domainvariable)
    is not working.