开发者

How to handle ampersands when finding/replacing text in batch file?

I have the following batch file to find and remove a string in a text file. The text files will be coming in the following format:

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

I simply want to remove "E:\MyDirectory\" from the file and then move the file to a subdirectory. My batch file works as expected except for the case wher开发者_运维百科e there is an ampersand in the file (such as the one above)..

Instead of my result file containing:

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

It instead contains,

079754,Billing 

I am somewhat new to writing batch files and I know the ampersand affects the tokenizing in some way. Any help would be greatly appreciated!

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


You should enquote commands like set, to escape the & and other special characters.
And use the delayed expansion, as with delayed expansion the special characters are ignored.
And percent expansion is evaluated before a block is executed, so your for-loop can't work as expected.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜