If the string that marks the end of a zone block is really consistent and distinctive -- e.g. every block ends with a line whose first character is "}", and this is only found at the end of a block -- you can use the input record separator variable "$/" to make this much easier.
#!/usr/bin/perl use strict; ( @ARGV == 2 and -f $ARGV[0] ) or die "Usage: $0 input.file domain.to.comment.out\n"; my ( $in_file, $rem_domain ) = @ARGV; open IN, "<", $in_file or die "$in_file: $!"; open OUT, ">", "$in_file.new" or die "$in_file.new: $!"; $/ = "\n}"; # input record separator is line-initial "}" while (<IN>) { # $_ contains a whole zone block if (/\W$rem_domain\W/) { s/^/#/; # add initial comment to block s/\n/\n#/g; # add comment after each "\n" } print OUT; }
The number of zone blocks that will be commented out in the file depends on what the user provides as the second command line arg on the script. I would recommend that you not rename the output to replace the input file as part of this script: the user should have a chance to confirm that the output file was changed as intended -- e.g. that there wasn't a mistake in the second command line arg.

(It could happen that someone hits the "Enter" key too soon, and comments all zone blocks that match an unintended substring.) BTW, this approach is also an easy way to uncomment a chosen block, in case you ever need that sort of tool.

(update: forgot mention: look up $/ in perlvar)


In reply to Re: Perl script to comment out lines in named.conf file by graff
in thread Perl script to comment out lines in named.conf file by firewall00

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.