Batch file 如何在循环中更改文件名而不使用感叹号?
脚本的问题是,如果文件有Batch file 如何在循环中更改文件名而不使用感叹号?,batch-file,Batch File,脚本的问题是,如果文件有,我将得到一个语法错误在其文件名中。我可以替换什么!文件名避免此错误?基本上,您需要切换延迟扩展,以便禁用变量时扩展变量的,如下所示: @echo关闭 setlocal DisableDelayedExpansion 对于%%j in(“*”)do( 设置“文件=%%~j” 设置“文件名=%%~nj” 设置“fileext=%%~xj” setlocal EnableDelayedExpansion 设置“文件名=!文件名:(1)=!” 如果不是“!filename!”=
,我将得到一个语法错误代码>在其文件名中
。我可以替换什么!文件名使用代码>避免此错误?基本上,您需要切换延迟扩展,以便禁用变量时扩展变量的,如下所示:
@echo关闭
setlocal DisableDelayedExpansion
对于%%j in(“*”)do(
设置“文件=%%~j”
设置“文件名=%%~nj”
设置“fileext=%%~xj”
setlocal EnableDelayedExpansion
设置“文件名=!文件名:(1)=!”
如果不是“!filename!”==”!fileext!”(
ren“!file!”!filename!!fileext!”
)
端部
)
除此之外,我还修改了引文。请注意,我没有进一步检查脚本的逻辑。执行任务,保持延迟扩展处于禁用状态。此外,以下注释的.bat
脚本尊重以下事实:
- 如果目标文件已经存在,则将失败(否则,将出现错误
存在重复的文件名,或者无法找到该文件
),并且
- 当前运行的
.bat
/.cmd
脚本无法重命名/删除
脚本正确地处理所有if,如插入符号、%
百分号等:
@echo off
setlocal enabledelayedexpansion
for %%j in ("*") do (
set filename=%%~nj
set filename="!filename:(1)=!"
if not "!filename!" == "%%~xj" ren "%%j" "!filename!%%~xj"
)
样本输出:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "filemask=*" original file mask
rem prepare background for debugging and demonstration
pushd "D:\bat\Unusual Names"
set "filemask=0*!*.txt" narrowed file mask
for %%j in ("%filemask%") do (
if /I "%%~fj"=="%~f0" (
rem do not rename currently running script "%~f0"
rem applicable if %filemask% does not exclude %~x0 extension i.e. .bat/.cmd
rem e.g. if "%filemask%"=="*"
) else (
set "file=%%~j" name and extension
set "filename=%%~nj" name only
set "fileext=%%~xj" extension only
call :renFile
)
)
popd
ENDLOCAL
goto :eof
:renFile
set "filename=%filename:(1)=%"
if not "%filename%%fileext%"=="%file%" (
if exist "%filename%%fileext%" (
rem renaming is not possible as target file already exists
echo ??? "%file%"
) else (
rem rename command is ECHOed merely for debugging and demonstration
rem make it operational no sooner than debugged
ECHO ren "%file%" "%filename%%fileext%"
)
) else (
rem output for debugging and demonstration
echo NER "%filename%%fileext%"
)
goto :eof
您应该签出-正则表达式文件重命名实用程序。然后,解决方案可以像调用jren“\(1\)”
==> dir /B "D:\bat\Unusual Names\0*!*.txt"
01exclam!ation(1).txt
02exc!lam!ation.txt
03exclam!ation!OS!(1).txt
04exc!lam!ation!OS!%OS%(1).txt
04exc!lam!ation!OS!%OS%.txt
==> D:\bat\SO\41714127.bat
ren "01exclam!ation(1).txt" "01exclam!ation.txt"
NER "02exc!lam!ation.txt"
ren "03exclam!ation!OS!(1).txt" "03exclam!ation!OS!.txt"
??? "04exc!lam!ation!OS!%OS%(1).txt"
NER "04exc!lam!ation!OS!%OS%.txt"
==>