2015-11-01 74 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

相关问题