簡體   English   中英

如何使用awk / sed命令在文件中查找塊並在特定位置插入字符串

[英]How to find a block in a file and insert a string at particular location using awk/sed commands

我的要求是讀取文件並在block []中找到一個字符串,然后插入一個新字符串,然后插入上面搜索的字符串。

例如,輸入文件中的數據看起來像

#starting of the file
[MAIN]    
.   
.   
.   
connection = TCPIP   
connection = HTTP   
connection = HTTPS   
.   
.   
.   

[TCPIP]   
name =  tcpip1   
port = 2222   
.   
.   
.   

[HTTP]   
name = http1   
port = 3333   
.    
.   
.

[HTTPS]   
name = https1   
port = 4444   
.   
.   
.   
#end of the file 

我的要求是
1)我需要在最后一次出現連接后在[MAIN]塊中插入一個新的連接(MQ)
2)我需要使用[MQ]在文件末尾插入一個塊,並插入所有必需的詳細信息

預期輸出應為

#starting of the file   
[MAIN]   
.   
.   
.   
connection = TCPIP   
connection = HTTP   
connection = HTTPS   
connection = MQ   
.   
.   
.   

[TCPIP]   
name =  tcpip1   
port = 2222   
.   
.   
.   

[HTTP]   
name = http1   
port = 3333   
.    
.   
.   
[HTTPS]   
name = https1   
port = 4444   
.   
.   
.   
[MQ]   
name = mq1   
port = 5555   
.   
.   
.   
#end of the file   

我嘗試使用awk和sed命令來查找字符串的出現並插入新的字符串。 但是,我沒有找到如何獲得字符串[connection]的最后一次出現。
您能告訴我如何實現嗎? 謝謝。

有幾種解決方法。 這是一種方法(帶有示例輸出):

$ awk '/\[MAIN\]/ {n=1;print;next} n==1 && /\[/ {n=0;print "CONNECTION=MQ\n"} {print} END {print "[MQ]\nname=mq1"}' input 
[MAIN]    
.   
.   
.   
connection = TCPIP   
connection = HTTP   
connection = HTTPS   
.   
.   
.   

CONNECTION=MQ

[TCPIP]   
name =  tcpip1   
port = 2222   
.   
.   
.   

[HTTP]   
name = http1   
port = 3333   
.    
.   
.

[HTTPS]   
name = https1   
port = 4444   
.   
[MQ]
name=mq1

讓我們依次查看每個awk語句:

  • /\\[MAIN\\]/ {n=1;print;next}

    這將檢查MAIN塊的開始。 如果開始,它將標志n為1,打印要輸出的行,然后跳轉以開始下一行。

  • n==1 && /\\[/ {n=0;print "CONNECTION=MQ\\n"}

    該語句在MAIN之后的第一個程序段的開頭執行。 在下一個塊的開始之前打印行CONNECTION=MQ 它還將標志n重置為零,以便我們知道已經離開了MAIN塊

  • {print}

    這只是將輸入線回顯到標准輸出。

  • END {print "[MQ]\\nname=mq1"}

    在文件末尾,這將打印出所需的新塊。

如何修改

awk不直接支持就地修改源文件。 但是,相同的效果很容易實現:

mv -f input input.bak && awk '/^\[MAIN\]/ {n=1;print;next} n==1 && /^\[/ {n=0;print "CONNECTION=MQ\n"} {print} END {print "[MQ]\nname=mq1"}' input.bak >input

上面的代碼創建了原始文件的備份副本,然后使用修改后的版本覆蓋了原始文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM