Monday, 9 September 2013

Avoid interpolations when reading lines via Windows batch file

Avoid interpolations when reading lines via Windows batch file

I'd like to use a simple Windows Batch file to do a text search and
replace within many files. My problem is: I do not know how to avoid
interpolating variables when reading lines from a target file that may
contain special variables/characters.
For example, with a target file, test.txt, that contains these lines
(including !time! and ^^!):
bbb aaaa bbb
!time!
bbb
^^!
And with a batch file like this:
@echo off
setlocal EnableDelayedExpansion
set SEARCH=a
set REPLACE=x
set FILE=test.txt
for /f "delims=" %%A in (%FILE%) DO (
set line=%%A
set line=!line:%SEARCH%=%REPLACE%!
echo !line!
)
I get the following output:
bbb xxxx bbb
18:51:27.00
bbb
^
But I want this output (preserving !time! and ^^!):
bbb xxxx bbb
!time!
bbb
^^!
Are there any tricks to avoid the interpolation, while still using a
simple Windows Batch script?

No comments:

Post a Comment