1

我正在编写一个脚本,用于在与文件名相对应的文件夹中复制文件,并且我使用 FOR 循环解决了该部分,该循环检查以确保目标文件夹存在并在验证后复制文件确实如此. 示例:11-01111_ABC_DEF.pdf 将进入 /11/0111/。长度可能会相差一两个字符,但格式是一致的。我在下面复制了我的基本脚本。

我的问题是有时需要处理同名文件。如果目标文件夹中已存在一个或多个文件副本,我该如何将数字连接到文件末尾?

setlocal enableextensions enabledelayedexpansion
for %%x in (*.PDF *.TXT) do (
  set "source="C:\files"
  set "dest=R:\"  
  set "filename=%%x"
  set "prefix=!filename:~0,2!"
  set "folder=!filename:~3,5!"

  if not exist !dest!\!prefix!\!folder! MOVE !filename! !source!\failed 
  if exist !source!\!filename! MOVE !filename! !dest!\!prefix!\!folder! 
)
4

2 回答 2

0
setlocal ENABLEDELAYEDEXPANSION
set "dest=worked"
for %%i in (*.pdf *.txt) do (
   for /f "tokens=1-3* delims=-_." %%j in ("%%i") do (
      if exist "%dest%\%%j\%%k" if exist "%dest%\%%j\%%k\%%i" if exist "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" (
     for /f "tokens=1-9* delims=-_." %%n in ('dir %dest%\%%j\%%k\%%j-%%k*-* /b') do set /a inc=%%p
     set /a inc+=1
     move "%%i" "%dest%\%%j\%%k\%%j-%%k-!inc!_%%l_%%m" || move "%%~i" "failed"
     set inc=
     )
      if exist "%dest%\%%j\%%k\%%i" if not exist "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" (
     move "%%i" "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" || move "%%~i" "failed"
     )
      if exist "%dest%\%%j\%%k" if not exist "%dest%\%%j\%%k\%%~i" (
     move "%%~i" "%dest%\%%j\%%k\%%~i" || move "%%~i" "failed"
     )
      if not exist "%dest%\%%j\%%k" move "%%~i" "failed"
      )
)

如果您希望我更改某些内容,请将其放在带有 .txts 和 .pdfs 注释的文件夹中。

于 2013-10-09T01:42:06.840 回答
-1
setlocal EnableDelayedExpansion
rem Set the maximum number of repeated names (keep it low):
set maxNumber=9

set "source=C:\files"
set "dest=R:\"  
for %%x in (*.PDF *.TXT) do (
  for /F "tokens=1,2 delims=-_" %%a in ("%%x") do (
    set "prefix=%%a"
    set "folder=%%b"
  )
  set "filename=%%x"

  if not exist %dest%\!prefix!\!folder! MOVE !filename! %source%\failed

  if exist %source%\!filename! (
    set "destname=!filename!"
    rem If destination filename already exists: concatenate a sequential number
    if exist %dest%\!prefix!\!folder!\!destname! (
      set "filename=%%~Nx"
      set "destname="
      for /L %%i in (1,1,%maxNumber%) do if not defined destname (
        if not exist %dest%\!prefix!\!folder!\!filename!-%%i%%~Xx set destname=!filename!-%%i%%~Xx
      )
    )
    MOVE !filename! %dest%\!prefix!\!folder!\!destname!
  )
)
于 2013-10-23T01:43:21.983 回答