如何在循环中更改文件名而不会出现感叹号问题?

时间:2017-01-18 08:04:56

标签: batch-file

@echo off
setlocal enabledelayedexpansion
for %%j in ("*") do (
    set filename=%%~nj
    set filename="!filename:(1)=!"
    if not "!filename!" == "%%~xj" ren "%%j" "!filename!%%~xj"
)

脚本的问题是如果文件!中有filename,我将收到语法错误。我可以用!filename!替换什么来避免此错误?

2 个答案:

答案 0 :(得分:0)

基本上,您需要切换延迟扩展,以便for变量在禁用时展开 - 如下所示:

@echo off
setlocal DisableDelayedExpansion
for %%j in ("*") do (
    set "file=%%~j"
    set "filename=%%~nj"
    set "fileext=%%~xj"
    setlocal EnableDelayedExpansion
    set "filename=!filename:(1)=!"
    if not "!filename!"=="!fileext!" (
        ren "!file!" "!filename!!fileext!"
    )
    endlocal
)

除此之外,我更正了报价。请注意,我没有进一步检查脚本的逻辑。

答案 1 :(得分:0)

执行任务保持延迟扩展禁用 。此外,评论 A duplicate file name exists, or the file cannot be found脚本遵循

的事实
    如果目标文件已存在,则
  • rename command将失败(否则会引发错误.bat),并且
  • 当前正在运行的.cmd / ^脚本无法重命名/删除。

如果cmd/.bat special characters符合%插入符号,@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 百分号等,该脚本会正确处理所有valid in file names

==> 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"

==>

示例输出

1