2015-11-01 72 views
1

以下腳本似乎替換每個第二個實例。 - 任何想法如何調整awk命令,使其僅替換第二個實例一次?如何用awk替換第二個實例一次

腳本位置,是指一個名爲basicTest.jmx文件,其中包含以下TXT

hashTree 
hashTree 
hashTree 
hashTree 
hashTree 
hashTree 
hashTree 

這裏的腳本:

scriptLocation="basicTest.jmx" 

myVar="FOOO__BARRRR" 

awkOut=$(awk -v s='hashTree' -v myVar="$myVar" '$0~s{c++} c==2{sub(s, myVar); c=0} 1' "${scriptLocation}") 
echo "$awkOut" > $scriptLocation 

這是我所需要的輸出看起來像:

hashTree 
FOOO__BARRRR 
hashTree 
hashTree 
hashTree 
hashTree 
hashTree 

這是目前的錯誤輸出:

hashTree 
FOOO__BARRRR 
hashTree 
FOOO__BARRRR 
hashTree 
FOOO__BARRRR 
hashTree 
+0

您確定您必須在腳本中重置c = 0嗎? –

+0

我刪除了C = 0和嘿賓果它工作 - 謝謝 – user1654528

回答

0

刪除C = 0解決了這一問題:工作版本below.-感謝所有的協助。

awkOut=$(awk -v s='hashTree' -v myVar="$myVar" '$0~s{c++} c==2{sub(s, myVar); } 1' "${scriptLocation}") 
1
$ awk -va=hashTree -vb=FOOO__BARRRR '$1~a&&++c==2{$1=b}1' filename 
hashTree 
FOOO__BARRRR 
hashTree 
hashTree 
hashTree 
hashTree 
hashTree 
+0

請解釋該代碼... – aschipfl

+0

請添加一個解釋給你答案,以便其他人可以很容易地理解你的代碼。 – Brody

+0

@Brody對不起!我的英語不好。我不能用英文解釋 – bian

相關問題