2013-06-27 107 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 –

相關問題