如何寻找/批处理文件替换文本时处理&符号? [英] How to handle ampersands when finding/replacing text in batch file?
问题描述
我有以下批处理文件找到,并在一个文本文件中删除的字符串。该文本文件将在以下格式来:
079754,计费和放大器;商务进阶..,E:\\ MyDirectory \\ 079754_35931_Billing&安培;商务进阶... PDF,PDF合并
我只是想去掉E:\\ MyDirectory \\从文件,然后将文件移动到子目录。我的批处理文件,按预期工作,除了那里是在文件中的符号的情况下(如一个以上)。
而不是包含我的结果文件:
079754,计费和放大器;商务进阶..,计费和放大器;商务进阶... PDF,PDF合并
相反,它包含了,
079754,计费
我有些新的编写批处理文件和我认识的符号影响以某种方式标记化。任何帮助将大大AP preciated!
批处理文件:
关闭@echo
CD C:\\ TEMP \\经纪商
在%% F(* .DAT)做(
如果存在newfile.txt德尔newfile.txt
FOR / F令牌= * delims =%%一中(%% f)作@call:改变一%%
德尔%%˚F
重命名newfile.txt %%˚F
移动%% F进口\\ %% F
)退出/ B
暂停:更改
设置文本=%〜1
设置文本=%文本:E:\\ MyDirectory \\ =%FOR / F令牌= 3 delims =%% d。在(%文本%)做@set文件= %%ð
(回声%文本%)GT;> newfile.txt
将%文件%,进口\\%文件%
退出/ B
您应该enquote像设置
,以躲避&放命令;
和其他特殊字符。结果
并使用延迟扩展,延迟扩展的特殊字符将被忽略。结果
并且执行了块之前百分号展开评估,所以你的for循环如预期不能工作。
SETLOCAL EnableDelayedExpansion
...:更改
设置文本=%〜1
设置文本=文本:E:\\ MyDirectory \\ =!FOR / F令牌= 3 delims =%% d。在(!的文字!)做@set文件= %%ð
(文呼应!)GT;> newfile.txt
动!文件! 进口\\!文件!
退出/ B
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 where 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
这篇关于如何寻找/批处理文件替换文本时处理&符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!