我真的很想知道为什么我的字符串替换过程在解析包含任何特殊字符(包括感叹号)的文本文件时有效。我预计延迟变量扩展会关闭&符号,百分号等的特殊含义,但会因感叹号而失败......
代码:
@echo on & setlocal ENABLEEXTENSIONS
set "InFile=%~1"
set "OutFile=%~2"
set "Replace=%~3"
CALL :ParseCue "%%InFile%%" "%%OutFile%%" "%%Replace%%"
endlocal &GOTO:EOF
:ParseCue
@echo on & setlocal ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
set "FileToParse=%~1"
set "OutputFile=%~2"
set "NewExtension=%~3"
for /F "usebackq tokens=* delims=" %%a in ("%FileToParse%") DO (
set "line=%%a"
@echo on & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set "line=!line:.wav=%NewExtension%!"
echo(!line!>>"%OutputFile%"
endlocal
)
endlocal &GOTO:EOF
输入文件.txt:
This a test for parsing lines with special characters
Rock & Roll.wav
Rock & Roll!.wav
Special | < > ~ \ ²³ { [ ] } ! " ´ ' ` üäö @ ; : € $ % & / ( ) = ? chars.wav
命令行语法:
D:\Users\Public\Batch\YAET>parse.bat "InputFile.txt" "OutputFile.txt" ".flac"
输出文件.txt:
This a test for parsing lines with special characters
Rock & Roll.flac
Rock & Roll!.flac
Special | < > ~ \ ²³ { [ ] } ! " ´ ' ` üäö @ ; : € $ % & / ( ) = ? chars.flac
编辑/补充:
1 1/2 年后,我不得不再次使用此代码段。请参阅另外两个处理毒字符的示例。第一个使用临时启用延迟扩展(参见 Ansgars 答案),第二个使用CALL
. 两者都将解析当前目录中和当前目录下非空文件的路径和名称,但没有尾随驱动器号和当前目录的路径。
示例#1(不需要在set "File=!File..."
and中加上双引号):echo "!FILE!">>...
@echo off & setlocal ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
del NonEmptyFiles.txt >NUL 2>&1
echo Searching non-empty files in and below current directory ...
for /f "tokens=*" %%I in ('dir /s /b /a:-D') do (
if not %%~zI==0 (
set "File=%%I"
setlocal ENABLEDELAYEDEXPANSION
set "File=!File:%cd%\=!"
echo "!File!">> NonEmptyFiles.txt
endlocal
)
)
echo Done. See NonEmptyFiles.txt.
endlocal &goto:EOF
示例 #2(速度较慢,需要用双引号括起来):
@echo off & setlocal ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
del NonEmptyFiles.txt >NUL 2>&1
echo Searching non-empty files in and below current directory ...
for /f "tokens=*" %%i in ('dir /s /b /a:-D') do (
if not %%~zi==0 (
set "File=%%i"
call set "File=%%File:%cd%\=%%"
call echo "%%File%%">> NonEmptyFiles.txt
)
)
echo Done. See NonEmptyFiles.txt.
endlocal &goto:EOF
用于测试的文件和文件夹:
D:\Martin\Any & Path>dir /s /b /a:-D
D:\Martin\Any & Path\Hello! World!.txt
D:\Martin\Any & Path\Rock & Roll\!File! !!File!!.txt
D:\Martin\Any & Path\Rock & Roll\%File% %%File%% %%I.txt
D:\Martin\Any & Path\Rock & Roll\Poison! !§$%&()=`´'_;,.-#+´^ßöäüÖÄÜ°^^#.txt
D:\Martin\Any & Path\Rock & Roll\SizeZero.txt
输出:
D:\Martin\Any & Path>stringinforloop.bat
Searching non-empty files in and below current directory ...
See NonEmptyFiles.txt. Done.
D:\Martin\Any & Path>type NonEmptyFiles.txt
"Hello! World!.txt"
"Rock & Roll\!File! !!File!!.txt"
"Rock & Roll\%File% %%File%% %%I.txt"
"Rock & Roll\Poison! !§$%&()=`´'_;,.-#+´^ßöäüÖÄÜ°^^#.txt"
享受批处理!马丁