在batch file中查找/replace文本时如何处理&符号?

我有以下batch file来查找和删除文本文件中的string。 文本文件将采用以下格式:

079754,Billing & Business Adv..,E:\MyDirectory\079754_35931_Billing & Business Adv...pdf,Combined PDF 

我只是想从文件中删除“E:\ MyDirectory \”,然后将文件移动到一个子目录。 我的batch file按预期工作,除了在文件中有一个&符(如上面的那个)的情况。

而不是我的结果文件包含:

 079754,Billing & Business Adv..,Billing & Business Adv...pdf,Combined PDF 

而是包含,

 079754,Billing 

我在写batch file方面有点新,而且我知道&符以某种方式影响了标记。 任何帮助将不胜感激!

batch file:

 @echo off cd C:\Temp\broker for %%f in (*.dat) do ( if exist newfile.txt del newfile.txt FOR /F "tokens=* delims=" %%a in (%%f) do @call :Change "%%a" del %%f rename newfile.txt %%f move %%f "import\%%f" ) exit /b pause :Change set Text=%~1 set Text=%Text:E:\MyDirectory\=% FOR /F "tokens=3 delims=," %%d in ("%Text%") do @set File=%%d (echo %Text%)>> newfile.txt move "%File%" "import\%File%" exit /b 

你应该像set一样set命令来转义&和其他特殊字符。
并且使用延迟扩展,因为延迟扩展,特殊字符被忽略。
百分比扩展在块被执行之前被评估,所以你的for循环不能按预期工作。

 setlocal EnableDelayedExpansion ... :Change set "Text=%~1" set "Text=!Text:E:\MyDirectory\=!" FOR /F "tokens=3 delims=," %%d in ("!Text!") do @set File=%%d (echo !Text!)>> newfile.txt move "!File!" "import\!File!" exit /b