@Echo Off
SetLocal EnableDelayedExpansion
Set _ScrFldr=%~dp0
PushD %_ScrFldr%
:: You can add other extensions to do multiple file types
For /F "Delims=" %%A In ('Dir /A-D /B *.txt') Do (
:: The space after the = is needed so we can Proper Case the first word
Set _FileName= %%A
:: Remove (, replace ( with _, replace - with _-_ ,
:: replace _ with space, and a first pass at removing multiple spaces
For %%I In ("%%~xA=" ".= " ")=" "(=_" "-=_-_" "_= " " = " **"!="**) Do Call Set
"_FileName=%%_FileName:%%~I%%"
:: Now make it all lower case, and another pass at removing multiple spaces
For %%I In ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i" "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r" "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z" " = ") Do Call Set "_FileName=%%_FileName:%%~I%%"
:: Proper Case and again remove multiple spaces
For %%I In (" a= A" " b= B" " c= C" " d= D" " e= E" " f= F" " g= G" " h= H" " i= I" " j= J" " k= K" " l= L" " m= M" " n= N" " o= O" " p= P" " q= Q" " r= R" " s= S" " t= T" " u= U" " v= V" " w= W" " x= X" " y= Y" " z= Z" " = ") Do Call Set "_FileName=%%_FileName:%%~I%%"
:: Last check for multiple spaces
Call :RmLoop
Set _FileName=!_FileName: = !
:: Remove any trailing underscore
Set _FileName=!_FileName:_%%~xA=%%~xA!
Ren "%%A" "!_FileName:~1!%%~xA"
)
PopD
Goto :EOF
:::::::::::::::::::::::::::::::::::::::::::::::
:RmLoop
Call Set "_FileName=%%_FileName: = %%"
Echo !_FileName!|Findstr /C:" ">Nul
If !ErrorLevel!==0 Goto RmLoop
这应该做的是从文件名和标题大小写中删除某些字符,即
some_filename = Some Filename
filename number 2 = Filename Number 2
大多数工作正常,例如更换大小写并删除多余的空格和下划线
但是我遇到了!
等特殊字符的问题(代码中有10行)
如果文件名被命名为文件! 2它被忽略
尝试使用"^!="
^"!="
,但无济于事
答案 0 :(得分:2)
如果变量包含!
或^
,则在展开FOR变量(如%% A)时,无法启用延迟展开。延迟扩展会破坏该值,因为单个!
被剥离,两个!
会将其间的字符解释为变量并将其展开(可能为空),^
将被剥离因为它用于逃避!
。
最简单的解决方案是将顶部更改为SETLOCAL DisableDelayedExpansion
,并使用您在其他地方使用的CALL command %%VAR%%
技巧替换所有延迟扩展。 CALL技巧比延迟扩展慢得多,所以通常我建议切换延迟扩展。但我认为在您的情况下切换可能会变得复杂。
我还建议你改变你的:RmLoop定义
:RmLoop
Call Set "_FileName2=%%_FileName: = %%"
If "%_FileName2%" neq "%_FileName%" (
set "_FileName=%_FileName2%"
goto :RmLoop
)
另外我不明白你打电话后为什么要用自己替换空间:RmLoop?
我不确定**"!="**
替换正在尝试什么。也许这可以删除?
答案 1 :(得分:0)
由于 管理进行排序将其添加到文件顶部
ps "!="
只是为了标记它出错的地方。
@Echo Off
SetLocal DisableDelayedExpansion
For /F "Tokens=*" %%J In ('Dir /B *.txt^|Findstr "!"') Do Call :Renamee "%%J"
..
..
..
..
..
::This at the very bottom
:Renamee
Set _FileTemp=%~1
Set _FileTemp=%_FileTemp:!=%
Ren "%~1" "%_FileTemp%"