2016-10-25 75 views
0

我想創建一個批處理腳本,它將從目錄和子目錄中將所有文件複製到具有特殊名稱的特定位置。使用具有特定命名要求的批處理腳本複製文件

subdir1_1111.txt 
subdir2_2222.txt 
subdir3_3333.txt 
subdir3_34rf.pdf 
subdir1_1111.txt 
. 
. 
subdir5_007.xlsx 

這裏:

我使用它我試圖複製文件LIST.TXT

D:\HOST\subdir1\1111.txt 
D:\HOST\subdir2\2222.txt 
D:\HOST\subdir3\3333.txt 
D:\HOST\subdir3\34rf.pdf 
D:\HOST\subdir4\4444.txt 
D:\HOST\subdir5\5555.txt 
D:\HOST\subdir5\5tg.xls 
D:\HOST\subdir5\subdir_55\007.xlsx 

內容的目標文件夾應包含文件作爲創建的列表HOST,subdir1到subdir 5和subdir_55都是子目錄。

這IAM嘗試使用下面的代碼給出:

@echo off & setlocal 
cd %~dp0 

IF EXIST list.txt del /F list.txt 
cd %~dp0\HOST 
dir /b /a-d /s *.* >> %~dp0\list.txt 
cd.. 

for /F "tokens=1-4 delims=\" %%a in (%~dp0\list.txt) do copy /b  %~dp0\HOST\%%c\%%d %~dp0\TARGET\%%c_%%d 

上面的代碼,只有當其內部subdir1沒有子目錄subdir5工作。我的要求是,如果還有n個子目錄,它應該複製文件。另一件事我不知道如何處理子目錄名稱與空間。

我知道它不會使用令牌,因爲可能有「n」個令牌,因爲主子目錄內可能有「n」個子目錄。

請幫助我。

+0

[Windows命令提示符(cmd)不是MS-DOS !!](https://scalibq.wordpress.com/2012/05/23/the-windows-command-prompt-is-not-a- DOS提示符/) – aschipfl

回答

0

我建議使用for /F和分隔符做路徑的操作,使用for~ modifiers變量來代替。

我會做這樣的:

  • 迭代通過你的源文件目錄檢索直接子目錄的所有名稱,使用for /D循環;
  • 對於每個子目錄,通過for /R循環遞歸地收集所有文件;
  • 構建每個最終的目標文件名;

下面是代碼:

@echo off 
setlocal EnableExtensions DisableDelayedExpansion 

rem // Define constants here: 
set "_SOURCE=D:\HOST" & rem // (source root directory) 
set "_TARGET=D:\TARGET" & rem // (target root directory) 
set "_DIRPATT=*"  & rem // (pattern for names of immediate sub-directories) 
set "_FILPATT=*.*"  & rem // (pattern for names of files to copy) 
set "_SEPAR=_"   & rem // (separator character to build new file names) 

rem // Walk through immediate sub-directories of source root directory: 
for /D %%D in ("%_SOURCE%\%_DIRPATT%") do (
    rem /* Process each immediate sub-directory in a sub-routine; 
    rem `%%~fD` is the full path to the current sub-directory; 
    rem its pure name will be derived in the sub-routine: */ 
    call :PROCESS "%%~fD" "%_FILPATT%" "%_TARGET%" 
) 

endlocal 
exit /B 


:PROCESS val_directory val_pattern val_target 
rem /* Sub-routine to process a single sub-directory. Arguments: 
rem val_directory [%~1] sub-directory to process; 
rem val_pattern  [%~2] pattern for file names; 
rem val_target  [%~3] target directory; */ 
rem // Retrieve all files in the sub-directory recursively: 
for /R "%~1" %%F in ("%~2") do (
    rem /* Build target file path; `%~n1` is the base name of the sub-directory, 
    rem `%%~nxF` is the full name of the currently iterated file; 
    rem then check whether the target file already exists: */ 
    if not exist "%~3\%~n1%_SEPAR%%%~nxF" (
     rem /* Target file does not exist, so copy the file; 
     rem `%%~fF` is the full path of the currently iterated source file: */ 
     copy /Y "%%~fF" "%~3\%~n1%_SEPAR%%%~nxF" 
    ) 
) 
exit /B 

如果目標文件已經存在,它不會被覆蓋;如果您確實想在這種情況下進行覆蓋,只需在copy命令行周圍刪除if not exist查詢即可。

相關問題