2017-01-23 183 views
-2

找到pyhton解决方案here,但我需要基于批处理文件的解决方案。批处理文件根据部分文件名将文件移动到基​​于部分文件夹名称的文件夹

有很多文件:

  • SSP4325_blah-等等,blah.xml
  • JKP7645_blah.xml
  • YTG6457-等等,blah.xml

和文件夹名称其中包含一段文件名:

  • REFID - SSP4325,JKP7645,GHT1278,YRR0023
  • REFID - YTG6457

我正在寻找一个批次的解决方案,将在前面读取的文件名的一部分(在第一个破折号或下划线之前),然后将该文件移动到文件名前面存在的文件夹中作为文件夹名称的一部分。

所以在上面的例子中,前两个文件(SSP4325和JKP7645)被移入第一个文件夹,因为它包含了文本作为文件夹名称的一部分。

第三个文件将被移动到第二个文件夹中。

我有数百个文件和63个文件夹。所以我希望能够自动化。

由于环境的限制,无法使用Powershell或Python。所以希望有一个批处理文件的方法。

谢谢。肖恩。

回答

0
@ECHO OFF 
SETLOCAL 
SET "sourcedir=U:\sourcedir" 
SET "destdir=U:\destdir" 
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*.xml" ' 
) DO (
FOR /f "tokens=1delims=_-" %%b IN ("%%a") DO (
    FOR /f "delims=" %%d IN (
    'dir /b /ad "%destdir%\*%%b*" ' 
) DO (
    ECHO(MOVE "%%a" "%destdir%\%%d\" 
) 
) 
) 

GOTO :EOF 

你需要改变的sourcedirdestdir设置以适合你的情况。

所需的MOVE命令仅为ECHO用于测试目的。 确认命令正确后,将ECHO(MOVE更改为MOVE以实际移动文件。追加>nul打压报告消息(例如,1 file moved

建立目录后,外循环把文件名中%%a,下一个循环获取名称的第一部分,直到但不包括第一个-_ (指定的delims)转换为%%b

内部循环在目的地目录中找到包含%%b的目标目录并构建适当的move行。

1

该解决方案只检查文件夹一次,并将它们存储在数组中,因此该方法运行得更快。

@echo off 
setlocal EnableDelayedExpansion 

rem Process the folders 
set i=0 
for /D %%a in (*) do (

    rem Store this folder in the next array element 
    set /A i+=1 
    set "folder[!i!]=%%a" 

    rem Separate folder in parts and store the number of the array element in each one 
    for %%b in (%%a) do set "part[%%b]=!i!" 

) 

rem Process the files 
for %%a in (*.xml) do (

    rem Get the first part of name 
    for /F "delims=-_" %%b in ("%%a") do (

     rem If such a folder exists... 
     if defined part[%%b] (

     rem Get the number of the corresponding array element and move the file 
     for %%n in (!part[%%b]!) do ECHO move "%%a" "!folder[%%n]!" 

    ) else (

     echo No folder exists for this file: "%%a" 

    ) 

    ) 
) 

这种方法也有几个优点:您可以检查特定的文件夹不存在,或者获得文件的数量转移到的每个文件夹等,如果你不感兴趣的这些点,只是删除if命令并使代码更简单...

有关批处理文件中阵列管理的说明,请参阅this answer

相关问题