Search code examples
bashxmlstarlet

Using xmlstarlet and BASH, how can I update a value of an element based on the elements current value


Using xmlstarlet and BASH, how can I update the value of an element only when the elements has the literal string "${numberOFThreads}". I'm trying to replace the item only when the string ${numberOFThreads} occurs with the number 20.

Before:

<stringProp name="ThreadGroup.num_threads">"${numberOFThreads}"</stringProp>

After:

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

Test XML

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.8" jmeter="2.13 r1665067">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">${numberOFThreads}"</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <longProp name="ThreadGroup.start_time">1456663030000</longProp>
        <longProp name="ThreadGroup.end_time">1456663030000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree/>
    </hashTree>
  </hashTree>
</jmeterTestPlan>

Solution

  • You can filter for the value of element with [. = ".."]. You just have to be careful, when escaping the "$ characters:

     xmlstarlet ed -u "//stringProp[@name='ThreadGroup.num_threads' and . = '\"\${numberOFThreads}\"']" -v "20" /tmp/test.xml