Search code examples
bashawksedxmlstarlet

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


I'm trying to replace the value 10 with the value 5 where testname="TG1"

Change This:

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

To This:

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

Snippet Example

Before:

<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>

After:

<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>

Solution

  • Assuming you actually have valid XML, this is really an xpath problem:

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

    To save the file in place, change ed to ed --inplace