【问题标题】:Batch file to Move files based on part of filename, to folder based on part of folder name批处理文件根据部分文件名移动文件,根据部分文件夹名称移动到文件夹
【发布时间】:2017-06-07 20:55:59
【问题描述】:

找到了一个pyhton解决方案here,但我需要一个基于批处理文件的解决方案。

有很多文件:

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

以及文件夹名称中包含一段文件名:

  • RefID - SSP4325、JKP7645、GHT1278、YRR0023
  • RefID - YTG6457

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

因此,在上述示例中,前两个文件(SSP4325 和 JKP7645)被移动到第一个文件夹中,因为它包含该文本作为文件夹名称的一部分。

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

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

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

谢谢。肖恩。

【问题讨论】:

    标签: batch-file directory filenames batch-processing move


    【解决方案1】:
    @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 命令仅用于测试目的ECHOed。 验证命令正确后,将ECHO(MOVE 更改为MOVE 以实际移动文件。附加>nul 以禁止报告消息(例如1 file moved

    建立目录后,外循环将文件名放入%%a,下一个循环获取该名称的第一部分,直到但不包括第一个-_(指定的delims ) 进入%%b

    内部循环在目标目录中找到包含%%b 的目标目录,并构造一个适当的move 行。

    【讨论】:

      【解决方案2】:

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

      @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 给出了 Batch 文件中数组管理的说明。

      【讨论】: