user1654528
user1654528

Reputation: 405

How to replace the second instance just once using awk

The following script seems to replace every second instance. - Any ideas how I can adjust the awk command so that it replaces the second instance just once?

Script location refers to a file called basicTest.jmx, which contains the following txt

hashTree
hashTree
hashTree
hashTree
hashTree
hashTree
hashTree

Here's the script:

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

This is what I need the output to look like:

hashTree
FOOO__BARRRR
hashTree
hashTree
hashTree
hashTree
hashTree

This is the current erroneous output:

hashTree
FOOO__BARRRR
hashTree
FOOO__BARRRR
hashTree
FOOO__BARRRR
hashTree

Upvotes: 1

Views: 54

Answers (2)

user1654528
user1654528

Reputation: 405

removing c=0 fixed the problem: Working version below.- Thanks all for your assistance.

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

Upvotes: 0

bian
bian

Reputation: 1456

$ awk -va=hashTree -vb=FOOO__BARRRR '$1~a&&++c==2{$1=b}1' filename
hashTree
FOOO__BARRRR
hashTree
hashTree
hashTree
hashTree
hashTree

Upvotes: 1

Related Questions