[英]Windows Batch: Save new output files in new folder with name of source directory
[英]Copy file from source directory tree to new location using source folder as name
我有一個文件和文件夾目錄,例如:
\Parent
|-\Child
||-\Test
|||-\Content
|||-targetfile.ext.out
|-\AnotherChild
||-anothertargetfile.ext.out
我想將任何具有.ext.out的文件復制到另一個目錄,但要使用目錄結構對其進行重命名。
EG:targetfile.ext.out將被復制到名稱為“ ParentChildTestContent.ext.out”的已定義目錄中,而“ anothertargetfile.ext.out”將被復制到與“ AnotherChild.ext.out”相同的已定義目錄中。 為了簡化腳本,可以刪除.out。
只要文件夾結構的深度不超過22層,它就可以正常工作。
如您尚未指出“源”文件夾是否為驅動器的根目錄(假設您需要的最終名稱僅包含“源”及其以下文件夾),它使用pushd
和xcopy
檢索所需文件的相對路徑。 ,在反斜杠上拆分檢索到的列表,並將各部分連接到最終文件名中。
@echo off
setlocal enableextensions disabledelayedexpansion
set "source=d:\temp\k"
set "target=c:\somewhere"
pushd "%source%"
for /d %%w in ("."
) do for /f "tokens=1,* delims=:" %%x in ('xcopy /l /s "*.txt" "%temp%"'
) do for /f "tokens=1-22 delims=\" %%a in ("%%~y"
) do echo copy /y "%source%\%%~y" "%target%\%%~nxw%%a%%b%%c%%d%%e%%f%%g%%h%%i%%j%%k%%l%%m%%n%%o%%p%%q%%r%%s%%t%%u%%v"
popd
該腳本僅將所需的copy
命令回顯到控制台。 如果輸出正確,請刪除echo
命令。
我將使用DIR / S / B探索目錄及其子文件夾,並獲得易於使用的結果:
@echo off
setlocal ENABLEDELAYEDEXPANSION
set "DEST=.\output"
REM Get complete absolute path for every interesting file
for /f %%a in ('dir /S /B .\Parent\*txt') do (
REM Process name as desired
set "newName=%%a"
set "newName=!newName:\=_!"
set "newName=!newName:*Parent_=!"
copy %%a %DEST%\!newName!
)
該腳本應該很健壯-它使用一個名為repl.bat
的幫助程序批處理文件-從以下網址下載: https : repl.bat
將repl.bat
放在與批處理文件相同的文件夾中或路徑上的文件夾中。
將d:\\\\target
更改為所需的文件夾-必需使用雙\\
。
也更改\\parent
該腳本將創建一個名為temp.bat.txt
的批處理文件以復制到該文件,您可以在使用記事本之前在記事本中對其進行檢查。
@echo off
dir /b /s /a-d "\parent\*.ext.out" |repl "..(.*)\\(.*)\\.*\.(.*\..*)" "copy \q$&\q \qd:\\target\\$2.$3\q" x >temp.bat.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.