Problem with search and replace batch file
Asked Answered
R

2

2

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.

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>

I.e. stripping out the !.

Where am I going wrong? Any ideas?

Reyesreykjavik answered 2/12, 2010 at 10:11 Comment(1)
possible duplicate of Find a string and replace specific letters in batch fileSignificative
C
5

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
)

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.

Conjunction answered 2/12, 2010 at 13:27 Comment(0)
B
2

You need to create the empty file entities_1.xml, because for some obscure reason >> won't create it with cmd as shell.
So use TYPE NUL > entities_1.xml just before your FOR loop, to create a zero-byte long file.

Bose answered 5/12, 2010 at 22:38 Comment(1)
Also useful. Thank you Benoit.Reyesreykjavik

© 2022 - 2024 — McMap. All rights reserved.