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?

有帮助吗?

解决方案

The problem doesn't occur during the read. It happens when you attempt to expand the value of %%A and delayed expansion is enabled. It's a problem because delayed expansion occurs after FOR variable expansion. The solution is to toggle delayed expansion on and off as needed.

@echo off
setlocal DisableDelayedExpansion

set SEARCH=a
set REPLACE=x
set FILE=test.txt

for /f "delims=" %%A in (%FILE%) DO (
  set line=%%A
  setlocal enableDelayedExpansion
  set line=!line:%SEARCH%=%REPLACE%!
  echo !line!
  endlocal
)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top