搜索单词然后搜索下一个单词然后追加

时间:2013-06-27 10:50:35

标签: linux sed

我正在尝试使用sed在主机名中附加主机名,因为我需要添加多个主机,所以我想自动化它。我遇到以下情况:

示例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
        }

尝试实现的是将新主机附加到“host_name”行,但文件中出现了很多“host_name”,因此要为特定服务添加它,我搜索了“Service:System Uptime”然后在那里的第7行,我搜索“host_name”并附加新的主机。

我已经使用sed完成了我想要的事情:

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

现在的问题是,当有多个主机时,上面的sed命令失败,它会中断该行并附加主机。

有关于此的任何建议吗?

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解您的问题,但我无法根据您提供的配置文件片段重现它。 话虽如此,我相信以下命令大致相当于你的命令,并不依赖于基于“行数”的搜索。

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

答案 1 :(得分:2)

您为什么要使用sed?这是awk的作业:

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