use warnings; use strict; use autodie; BEGIN { # service(s) to exclude, command(s) to check. # string definitions must be quoted if they may contain whitespace. my @excluded_services = ('PING', ); my @check_commands = ('check_nrpe', ); # contact(s) to add. # string definitions must be quoted if they may contain whitespace. use constant AR_ADD_CONTACTS => [ qw(other folks) ]; my ($rx_excluded_services) = map qr{ \b (?: $_) \b }xms, join '|', map quotemeta, reverse sort @excluded_services ; my ($rx_check_commands) = map qr{ \b (?: $_) \b }xms, join '|', map quotemeta, reverse sort @check_commands ; # define constant-like subroutines to include lexicals. sub RX_EXCLUDE_SERVICES () { qr{ service_description [^\n\S]+ $rx_excluded_services }xms; } sub RX_CHECK_SERVICES () { qr{ check_command [^\n\S]+ \S* $rx_check_commands }xms; } sub RX_CONTACT_ENTRY () { qr{ contact_groups [^\n\S]+ \S+ }xms; } } # end BEGIN open my $fh_in, '<', 'kt.txt'; local $/ = '}'; # character ends of define service { ... } block BLOCK: while (my $block = <$fh_in>) { next BLOCK if $block =~ RX_EXCLUDE_SERVICES; next BLOCK unless $block =~ RX_CHECK_SERVICES; $block = add_contacts($block, RX_CONTACT_ENTRY, AR_ADD_CONTACTS); } continue { print $block; } # end while BLOCK close $fh_in; exit; # subroutines ###################################################### sub add_contacts { my ($block, # block to edit $rx_contact, # regex: contact entry in block $ar_add, # array ref.: contacts to add ) = @_; $block =~ s{ ($rx_contact) } { join ',', $1, @$ar_add }xmse; return $block; } #### c:\@Work\Perl\monks\catalyst_list>perl edit_nagios_cfg_2.pl define service { host_name kr-cont00 service_description PING check_command check_host max_check_attempts 1 check_interval 1 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins notification_interval 60 notification_period 24x7 notifications_enabled 1 register 1 } define service { host_name KT service_description Check SSH check_command check_ssh max_check_attempts 1 check_interval 1 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins notification_interval 60 notification_period 24x7 notifications_enabled 1 register 1 } define service { host_name KT service_description Controller Load check_command check_nrpe!check_load max_check_attempts 1 check_interval 1 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins,other,folks notification_interval 60 notification_period 24x7 notifications_enabled 1 register 1 }