问题的搜索和替换批处理文件 [英] Problem with search and replace batch file

查看:93
本文介绍了问题的搜索和替换批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,我有一个批处理文件来搜索该文件内的特定的字符串,与由用户定义的字符串替换它,然后将它输出到一个新的XML文件:

I have an XML file and I have a batch file to search for a specific string within that file, replace it with a string defined by the user and then output it to a new XML file:

@echo off > entities_1.xml
setLocal EnableDelayedExpansion

if exist entities_1.xml del entities_1.xml
set /p name= What is the new space NAME?

for /f "tokens=* delims= " %%G in (entities.xml) do (
set str=%%G
set str=!str:[Test Space]=[%name%]!
echo !str! >> entities_1.xml
)

这工作和[测试空间]的任何实例与用户定义的值替换。

This works and any instances of [Test Space] are replaced with the value defined by the user.

我的问题,然而,就是该批处理文件也剥出感叹号的实例(!)标记。因此,例如在XML有类似于此行:

My issue, however, is that the batch file is ALSO stripping out instances of exclamation (!) marks. So for example in the XML there are lines similar to this:

<property name="title"><![CDATA[TEST2]]></property>

在运行该批处理脚本,它与替换上面:

When the batch script is run, it is replacing the above with:

<property name="title"><[CDATA[TEST2]]></property>

即。剥出!

我在哪里去了?任何想法?

Where am I going wrong? Any ideas?

推荐答案

这是由设置STR容纳线的方式不对= %%摹而推迟扩充被启用。结果
这是因为延迟的扩张阶段是%% V扩展阶段之后。

It's the wrong way of receiving a line by set str=%%G while the delayed expansion is enabled.
It's because the delayed expansion phase is after the %%v expansion phase.

使用禁用延迟扩展你有问题,你不能替换字符串在一个安全的方式。
所以,你必须切换延迟扩展。

With disabled delayed expansion you got the problem, that you can not replace the string in a safe way. So you have to toggle the delayed expansion.

@echo off > entities_1.xml
setLocal DisableDelayedExpansion

if exist entities_1.xml del entities_1.xml
set /p name= What is the new space NAME?

for /f "tokens=* delims= " %%G in (entities.xml) do (
    set str=%%G
    setLocal EnableDelayedExpansion
    set str=!str:[Test Space]=[%name%]!
    >> entities_1.xml echo(!str!
    endlocal
)

切换重定向,所以你并不总是追加的空间。结果
使用回声(,让您得到的回声是如果!STR!是空的。

Switching the redirection, so you didn't append always a space.
Using echo(, so you get not echo is on if the !str! is empty.

这篇关于问题的搜索和替换批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆