sed替换第n个匹配项并保存到同一个文件

时间:2021-04-09 19:26:18

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将单词hashTree的第二个实例替换为ReplacedTxt,并更新文件Test1.jmx。由于某种原因,替换和文件更新不起作用.-任何想法?

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

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

Test1.jmx是我正在尝试更新的文件。

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.8" jmeter="2.13 r1665067">
  <hashTree>
    <hashTree> 
  </hashTree>
</jmeterTestPlan>

2 个解决方案

#1


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(即第4行是 而不仅仅是 ),您可以使用xmlstarlet执行此操作:

xml ed -r '/jmeterTestPlan/hashTree/hashTree' -v ReplacedTxt Test1.jmx

#2


-1  

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

使用AWK对帖子的引用给了我最好的解决方案:

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

#1


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(即第4行是 而不仅仅是 ),您可以使用xmlstarlet执行此操作:

xml ed -r '/jmeterTestPlan/hashTree/hashTree' -v ReplacedTxt Test1.jmx

#2


-1  

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

使用AWK对帖子的引用给了我最好的解决方案:

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