2013-06-27 135 views
1

我想要使用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”这么多的出现,因此要将其添加到我已搜索“服务:系统正常运行时间”的特定服务中,然后在第7行中搜索“host_name”并追加新的主机。

我已经做了我想用sed什么:

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

现在的问题是当有存在多个主机,则上述sed命令失败,它打破了线,并附加主机。

对此有何建议?

+0

也许你可以尝试使你的问题更清楚。例如,说明您在示例输入和所需输出方面遇到问题的情况。 –

回答

2

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

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

你为什么试图使用sed?这是awk的工作:

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

我正在使用awk,因为在awk中没有与'sed -i'等效的文件 –

+1

有一些,但它可用于'gawk v4.1'。 –

+0

你为什么要使用'-i'?!?!这就是重定向的目的。看到http://stackoverflow.com/questions/10829514/how-do-i-run-the-sed-command-with-input-and-output-as-the-same-file/10834267#10834267 –

相关问题