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?
CodePudding user response:
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
CodePudding user response:
with awk
awk '
$1 == "use" {use = $2}
use == "linux-service" && $1 == "contact_groups" {$0 = $0 ", contactgroup2"}
{print}
' file
To update the file:
gawk -i inplace '...' file
awk '...' file | sponge file
-- requiresmoreutils
packagef=$(mktemp); awk '...' file > "$f" && mv "$f" file