Rahul Patil
Rahul Patil

Reputation: 1034

Search word then search next word then append

I'm trying to append hostname in configuration file using sed, because there are multiple hosts that I need to add, so I want to to automate it. I am stuck with the following situation:

Example InputFile :

#######################################################################
#
#Service: System Uptime

#######################################################################

define service{
        use                            generic-service
        host_name                       host1,host2,host3,host4,host5,host6,host7,host8,host9,host10,host11,host12,host13,host14,host15,host16,host17,host18,host19,host20,host21,host22,host23,host24,host25,host26,host27,host28,host29,host30
        service_description            System Uptime
        is_volatile                    0
        check_period                   24x7
        contact_groups                 Test_group
        notification_options           c,w,r,u
        check_command                  check_nt_uptime
        max_check_attempts             3
        normal_check_interval          1
        retry_check_interval           1
        notification_interval          120
        notification_period            24x7
        }

What am trying to achieve is appending new hosts to "host_name" line, but there are so many occurrences of "host_name" in the file, so to add it for a specific service I have searched for "Service: System Uptime" then in the 7th line from there I search "host_name" and append new hosts.

I have done what I want using sed:

sed   '/Service: System Uptime/{N;N;N;N;N;N;N;N;/host_name/s|$|,NewHost|}' input file 

Now the problem is when there are multiple hosts in there then the above sed command fails, it breaks the line and appends the host.

Any suggestions on that?

Upvotes: 1

Views: 80

Answers (2)

William Pursell
William Pursell

Reputation: 212414

Why are you trying to use sed? This is a job for awk:

awk '/#Service: System Uptime/ {a=1} 
  a && /host_name/ { a=0; $0 = $0 ", new_host" } 1' input-file

Upvotes: 2

iruvar
iruvar

Reputation: 23374

I am not sure I understand your problem and I am unable to reproduce it based on the configuration file snippet you have provided. Having said that, I believe the following command is roughly equivalent to yours and does not depend on a "number of lines"-based seek.

sed   '/Service: System Uptime/,/host_name/{/host_name/s|$|,NewHost|}' input_file

Upvotes: 2

Related Questions