2017-01-23 193 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

相關問題