2011-04-21 122 views
2

我有以下批处理文件来查找和删除文本文件中的字符串。该文本文件将在以下格式来:在批处理文件中查找/替换文本时如何处理&符号?

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

我只是想去掉“E:\ mydirectory中\”从该文件,然后将文件移动到子目录。我的批处理文件,按预期工作,除了那里是在文件中的符号(如上面的一个)的情况下..

而是包含我的结果文件:

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

相反,它包含,

079754,Billing 

我在编写批处理文件方面有点新,而且我知道&符以某种方式影响标记化。任何帮助将不胜感激!

批处理文件:

@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 
+0

使用'^'来转义特殊字符(如&符号),即'^&'。 – 0xC0000022L 2011-04-21 13:36:03

+0

我无法控制输入。 – ntsue 2011-04-21 13:39:15

+0

是的。例如在你的'Change'子里面。使用字符串替换。虽然我不确定这会在这里有所作为。 – 0xC0000022L 2011-04-21 13:46:48

回答

5

你应该enquote命令,如set,为了躲避&和其他特殊字符。
并使用延迟扩展,因为延迟扩展,特殊字符被忽略。
在执行块之前评估百分比展开,因此您的for-loop无法按预期工作。

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 
+0

+1,在分配'%〜1'时完全错过了这个事实。 – 0xC0000022L 2011-04-21 14:06:32

+0

非常感谢! :d – ntsue 2011-04-21 14:35:49