0

I'm trying to use sed to replace the 2nd instance of the word hashTree with the word ReplacedTxt and update the file Test1.jmx. For some reason the replacing and file updating are not working.- Any ideas?

sed -i '' 's/hashTree/ReplacedTxt/2' Test1.jmx

Test1.jmx is my file that I'm trying to update.

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.8" jmeter="2.13 r1665067">
  <hashTree>
    <hashTree> 
  </hashTree>
</jmeterTestPlan>
Sascha
  • 398
  • 6
  • 14
  • 3
    My guess is that `/2` tells sed to replace the second match on every line. None of your lines have two matches. – melpomene Jul 18 '15 at 12:11
  • see [how-to-replace-the-second-instance-of-a-string-with-awk-sed](http://stackoverflow.com/questions/31489531/how-to-replace-the-second-instance-of-a-string-with-awk-sed) – amdixon Jul 18 '15 at 12:13
  • `sed` is line oriented so it doesn't track how many time it saw that word on previous lines. You might want to consider tools built since SGML came around. – chicks Jul 18 '15 at 12:14
  • Thanks I have been working with AWK. However I wanted a sed solution. I'll check out awk. thanks for your help – Sascha Jul 18 '15 at 12:18

2 Answers2

0

Assuming your file is actually valid XML (that is, the 4th line is <hashTree/> rather than just <hashTree>), you can do it with xmlstarlet:

xml ed -r '/jmeterTestPlan/hashTree/hashTree' -v ReplacedTxt Test1.jmx
lcd047
  • 5,731
  • 2
  • 28
  • 38
  • awkOut=$(awk -v s='' -v myVar="$myVar" '$0~s{c++} c==2{sub(s, myVar); c=0} 1' "${scriptLocation}") – Sascha Jul 19 '15 at 13:13
  • @Sascha There are probably at least 36 ways of doing this witk `awk`, `sed`, `grep`, and so on. The point I'm trying to make is that you [shouldn't parse XML with regexps](http://stackoverflow.com/a/1732454/1658042). – lcd047 Jul 19 '15 at 13:49
-1

The reference to the post with AWK gave me the best solution:

scriptLocation="Test1.jmx"
txtToAdd="$XML_DIR/perfXml.txt"
myVar=`cat txtToAdd`
awkOut=$(awk -v s='<hashTree>' -v myVar="$myVar" '$0~s{c++} c==2{sub(s, myVar); c=0} 1' "${scriptLocation}")
echo "$awkOut" > $scriptLocation
lcd047
  • 5,731
  • 2
  • 28
  • 38
Sascha
  • 398
  • 6
  • 14