在特定字符后重命名文件

时间:2016-08-13 17:18:19

标签: windows batch-file automation batch-rename

希望能在这里得到一些帮助。我有一堆文件被监控,结束设施被删除,文件如下所示:

LastName,FirstName_DOS-Facility.pdf

我目前运行以下内容:

@echo off

for /F "tokens=1,* delims=-" %%a in ('dir /A-D /B "*.pdf"') do (
    ECHO move "%%a-%%b" "%%a%%~xb"
)

它创建了LastName,FirstName_DOS.pdf

我遇到的问题是具有相同名称的多个文件,我的批处理文件只是用较新的文件替换旧文件。如果需要,有没有办法附加_1.pdf _2.pdf _3.pdf等?谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

以下是适合您的任务要求的注释批处理代码。

@echo off
setlocal EnableExtensions EnableDelayedExpansion

for /F "tokens=1* delims=-" %%a in ('dir "*-*.pdf" /A-D /B 2^>nul') do (
    if not exist "%%a%%~xb" (
        ren "%%a-%%b" "%%a%%~xb"
    ) else (
        call :GetNextAppendix "%%a" "%%~xb"
        ren "%%a-%%b" "%%a!NextAppendix!%%~xb"
    )
)

endlocal
goto :EOF

rem This subroutine inserts between file name passed as first argument
rem and file extension passed as second argument an underscore and an
rem incrementing number in range 1 to 50000 and checks if a file with
rem this name already exists. If there is no file with current number
rem in file name, this number with the preceding underscore is assigned
rem to an environment variable used in parent process routine to rename
rem the file.

:GetNextAppendix
for /L %%I in (1,1,50000) do (
    if not exist "%~1_%%I%~2" (
        set "NextAppendix=_%%I"
        goto :EOF
    )
)

rem Windows command interpreter should never reach this part of the code.
rem But in case of this really happens, simply clear the appendix variable
rem which results in a failed renaming of file in parent process loop 
rem above with output of an error message because of file already existing.

set "NextAppendix="
goto :EOF

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • call /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • ren /?
  • set /?
  • setlocal /?

另请参阅微软关于Using command redirection operators的文章,其中2^>nul的解释为2>nul,其中重定向操作符>与[{1}}一起转发,以便应用于^执行命令 DIR ,并且不会被解释为命令行中无效位置的命令 FOR 的重定向操作。

这会将 DIR 输出的错误消息重定向到与 STDERR 到设备 NUL 的通配符模式*-*.pdf不匹配的文件抑制它。

答案 1 :(得分:0)

将脚本保存到 test.bat 并从打开的Cmd提示符运行。将 dir 值替换为您的路径。如果有任何错误,请告诉我。

@echo off
setlocal enabledelayedexpansion
set "dir=C:\My_Files"
pushd "%dir%"
for /F "tokens=1,* delims=-" %%a in ('dir /A-D /B "*.pdf" 2^>nul') do (
    call :rename %%a %%b )
popd
exit /b

:rename
set "i="
:loop
if exist "%1!i!%~x2" (set /a "i+=1" & goto :loop)
ren "%1-%2" "%1!i!%~x2"
exit /b
相关问题