How to replaces a value in a file after a particular string using perl?

I need to replace the value of notifications_enabled to 0 if the value already set to 1 and vice versa(not the other values and spaces remain same after the value changed). I tried the below program for that. Can any one help me out.

file:test.cfg

define host {
                   hostgroups                    linux-servers
                   max_check_attempts            5
                   check_interval                5
                   retry_interval                1
                   notification_interval        60
                   notifications_enabled         1
                 }  

script:

#!/usr/bin/perl
use strict;
use vars qw( @value $status $line);

@value = `grep -i notifications_enabled /root/test.cfg`;
 open(FILE,"/root/test.cfg") || die unable to open the config_file;
 while ($line = <FILE>)
 {
   chomp $line;
   @value = `grep -i notifications_enabled /root/test.cfg`;
   $status = (split(/\s{2,}/,$value[0]))[1];
 }
print "$status\n";
close(FILE);

open(FILE,">>/root/test.cfg") || die unable to open the config_file;
while ( $line = <FILE>)
{
  print "$status";
if ( $status == 1) {
         $status = 0;
 }
}
close(FILE);
$ cat tmp/tmp.dat
define host {
    hostgroups                    linux-servers
    max_check_attempts            5
    check_interval                5
    retry_interval                1
    notification_interval        60
    notifications_enabled         0
}


$ perl -pi -e's/(notifications_enabled\s*)(\d+)/$sub = "$1" . ("$2"== "0" ? "1":"0")/e; ' tmp/tmp.dat


$ cat tmp/tmp.dat
define host {
    hostgroups                    linux-servers
    max_check_attempts            5
    check_interval                5
    retry_interval                1
    notification_interval        60
    notifications_enabled         1
}

Thanks :slight_smile: ...it's working fine.