2016-08-13 10 views
0

希望在此获得一些帮助。我有一堆被监视的文件,并删除结束设施,文件看起来如下:在特定字符后重命名文件

姓氏,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等的方法?感谢您的帮助!

回答

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 operators2^>nul的解释是2>nul与重定向操作>逃脱^在命令DIR的执行中进行,而不能解释为重定向操作命令FOR在命令行中的无效位置。

此上没有文件从STDERR通配符模式*-*.pdf匹配设备NUL抑制其重定向由DIR误差输出消息。

+0

完成了!非常感谢!!现在,如果我可以找到一种方法来读取文件名中的DOS,创建一个文件夹(或只是移动文件,如果存在的话)并移动文件,我的生活会更容易! –

0

将脚本保存到test.bat并从打开的Cmd提示符运行。用您的路径替换目录值。让我知道是否有任何错误。

@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 
+0

请用Upvote并使用Answer Box左侧的按钮接受符合您需求的答案。 – sambul35

+0

感谢您的回复!该脚本只是给出了“系统找不到指定的文件”错误,两次。在文件夹中有两个.pdf。 –

+0

更新了脚本。你用自己的路径替换了_dir_路径吗? – sambul35

相关问题