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

时间:2016-07-02 13:48:32

标签: bash awk sed xmlstarlet

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

改变这个:

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

To This:

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

3 个答案:

答案 0 :(得分:2)

假设您确实拥有有效的XML,这实际上是一个xpath问题:

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

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

答案 1 :(得分:0)

试试这个awk-command:

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

如果name="ThreadGroup.num_threads">10</stringProp>位于name="ThreadGroup.num_threads">5</stringProp>

之内,它会将所有<... testclass="ThreadGroup" testname="TG1" ...>替换为<dict> <key>CFBundleTypeName</key> <string>My File Format</string> <key>CFBundleTypeIconFiles</key> <array> <string>MySmallIcon.png</string> <string>MyLargeIcon.png</string> </array> <key>LSItemContentTypes</key> <array> <string>com.example.myformat</string> </array> <key>LSHandlerRank</key> <string>Owner</string> </dict>

答案 2 :(得分:0)

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>