I am working on a script to make changes to a Nagios plugin service definition using BASH. I need to append the contact group name line but only for certain service definitions. So I would start with this.
define service {
use sites-service
host_name my_host
service_description check_reboot_os_updates
check_command check_reboot_os_updates
contact_groups contactgroup1
servicegroups MyGroup
}
define service {
use linux-service
host_name my_host
service_description other_description
check_command other_command
contact_groups contactgroup1
servicegroups MyGroup
}
And I want to append only select contact group lines. So say I wanted to add an additional contact group to the Linux services like this.
define service {
use sites-service
host_name my_host
service_description check_reboot_os_updates
check_command check_reboot_os_updates
contact_groups contactgroup1
servicegroups MyGroup
}
define service {
use linux-service
host_name my_host
service_description other_description
check_command other_command
contact_groups contactgroup1, contactgroup2
servicegroups MyGroup
}
Is there a way I can do this using sed or awk or something else?
Using sed
, if the string linux-service
is unique, you can try matching from the line containing the string to the line containing the string contact_groups
appending the additional group within the match.
$ sed '/linux-service/,/contact_groups/s/contact_groups.*/&, contactgroup2/' input_file
define service {
use sites-service
host_name my_host
service_description check_reboot_os_updates
check_command check_reboot_os_updates
contact_groups contactgroup1
servicegroups MyGroup
}
define service {
use linux-service
host_name my_host
service_description other_description
check_command other_command
contact_groups contactgroup1, contactgroup2
servicegroups MyGroup