Home:ALL Converter>Avoid interpolations when reading lines via Windows batch file

Avoid interpolations when reading lines via Windows batch file

Ask Time:2013-09-10T07:10:22         Author:ALF

Json Formatter

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?

Author:ALF,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18708441/avoid-interpolations-when-reading-lines-via-windows-batch-file
yy