用批处理文件中的特殊字符替换标记

时间:2013-07-29 21:01:31

标签: batch-file

我有一个包含xml标题和xml页脚的xml文件,我想删除页眉和页脚并将内容存储在变量中。 xml文件的内容在循环内发生变化。

例如:

for (some range) do (
set "xmlHeader=<?xml version="1.0" encoding="UTF-8"?><Config  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">"
set "xmlFooter=</Config>"

<then get and set variable from xml file>
)

xml文件包含:

<?xml version="1.0" encoding="UTF-8"?><Config  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<tag1>info1 changes in the loop</tag1>
<tag2>info2 changes in the loop</tag2>
</Config>

我希望批量存储变量

<tag1>info1</tag1>
<tag2>info2</tag2>

我试过了:

for (outer loop condition ) do (
for /f "Tokens=* Delims=" %%c in (xmlFile.xml) do set config=%%c
"!config:%xmlHeader%=!"
echo "!config!"
)

但是替换没有做任何事情。请帮忙!谢谢。

2 个答案:

答案 0 :(得分:3)

使用sed for Windows尝试:

示例:

    >type file
    <?xml version="1.0" encoding="UTF-8"?><Config  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
    <tag1>info1 changes in the loop</tag1>
    <tag2>info2 changes in the loop</tag2>
    </Config>

    >sed -r "\#xml version|</Config>#d; s#^(<[^>]+>\S+)[^<]+(<[^>]+>)#\1\2#" file
    <tag1>info1</tag1>
    <tag2>info2</tag2>

答案 1 :(得分:2)

批量字符串替换

%Var:Term=Replace%

使用批处理字符串替换时必须遵循的一些规则

  • 要替换的字符串(搜索词)可能不包含以下任何字符
    • 等号=(因为这就是它知道搜索词的结束方式)
  • 要替换的字符串(搜索词)不能以下列字符开头
    • Tilde ~(因为这是批处理字符串的特殊字符)
    • Asterisk *(因为这是批处理字符串的特殊字符)

解决方案

请参阅DBenham的http://www.dostips.com/forum/viewtopic.php?f=3&t=2710获得100%批量解决方案。

请参阅DBenham的https://stackoverflow.com/a/16735079/891976了解Batch / JScript混合解决方案。

请参阅https://gist.github.com/DavidRuhmann/4608317了解我的100%批次概念证明。

相关问题