如何使用 sed、awk 或理想情况下的 xmlstartlet 替换 XML 文件中基于元素名称的值

How can I replace a value based on an element name in my XML file using sed, awk or ideally xmlstartlet

我正在尝试将值 10 替换为值 5,其中 testname="TG1"

改变这个:

<stringProp name="ThreadGroup.num_threads">10</stringProp>

为此:

 <stringProp name="ThreadGroup.num_threads">5</stringProp>

片段示例

之前:

<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TG1" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">10</stringProp>
  </ThreadGroup>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TG2" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">50</stringProp>
  </ThreadGroup>

之后:

<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TG1" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">5</stringProp>
  </ThreadGroup>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TG2" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">50</stringProp>
  </ThreadGroup>

试试这个 awk 命令:

awk '[=10=] ~ "testclass=\"ThreadGroup\"" && [=10=] ~ "testname=\"TG1\""{replace=1}
     [=10=] ~ "testclass=\"ThreadGroup\"" && [=10=] !~ "testname=\"TG1\""{replace=0}
     replace{gsub("name=\"ThreadGroup.num_threads\">10</stringProp>",
                  "name=\"ThreadGroup.num_threads\">5</stringProp>",[=10=])}1' in.txt

如果它们在 <... testclass="ThreadGroup" testname="TG1" ...>

内,它将用 name="ThreadGroup.num_threads">5</stringProp> 替换所有 name="ThreadGroup.num_threads">10</stringProp>

假设你确实有有效的 XML,这确实是一个 xpath 问题:

xmlstarlet ed \
    --update '//ThreadGroup[@testname="TG1"]//stringProp[@name="ThreadGroup.num_threads"]' \
    --value 5 \
    file.xml

要将文件保存到位,请将 ed 更改为 ed --inplace

awk '{sub(/10<\/stringProp>/,"5</stringProp>")}1' file

<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TG1" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">5</stringProp>
  </ThreadGroup>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TG2" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">50</stringProp>
  </ThreadGroup>