我對 Windows Bat 檔案程式設計不是很熟悉,如果有任何幫助,我將不勝感激。
我需要一個bat檔來執行以下操作:
- 從檔案名稱中提取資料夾名稱 - 例如,從檔案名稱“123-Chemistry-101.rep”中提取 Chemistry。 「-」可用於表示標記的開始和結束。
- 將相同檔案移到名為 Chemistry 的資料夾中。化學將是所有報告所在的子目錄。
我可能可以完成它的第二部分(我在這個網站上找到的),但第一部分超出了我的能力。
例如,對於 (*.rep) 中的 /RU:\Test %%f 複製 %%f U:\test\Chemistry\
問候,杜蘭德
答案1
您要求Batch
,但我回答,Powershell
因為我認為今天Batch
對於這樣的任務有點過時,希望您的系統支援Powershell
:
$rootDir = "U:\Test"
$files = Get-ChildItem $rootDir -Filter *.rep
foreach($file in $files) {
$folder = $file.toString().split("-")[1]
$sourcefile = "$rootDir\$file"
$targetdir = "$rootDir\$folder"
if(!(Test-Path -Path $targetdir )){
New-Item -ItemType directory -Path $targetdir
}
Move-Item $sourcefile $targetdir
}
編輯@Karan:
遞歸(保留子目錄樹):
$rootDir = "U:\Test"
$files = Get-ChildItem $rootDir -Filter *.rep -Recurse
foreach($file in $files) {
$sourcefile = $file.Fullname
$filepath = $file.PSParentPath
$newfoldertocreate=$file.toString().split("-")[1]
if(!(Test-Path -Path $filepath\$newfoldertocreate)){
New-Item -ItemType directory -Path $filepath\$newfoldertocreate
}
Move-Item $sourcefile $filepath\$newfoldertocreate
}
答案2
從父資料夾執行此批次文件報告資料夾:
for /f "delims=" %%a in ('dir /b /s "Reports folder\*.rep"') do for /f "tokens=2 delims=-" %%i in ("%%~a") do (
if not exist "%%~dpa%%i\" md "%%~dpa%%i"
move "%%~a" "%%~dpa%%i\"
)
%%a和%%i是兩者使用的變數為了前者包含 .REP 檔案的完整路徑(由外循環提供),後者包含從檔案名稱中提取的資料夾名稱(由內循環提供)。
for /?
任何有興趣的人都應該真正尋求更多幫助(請注意,在批次文件中,% 符號加倍):
%~I - expands %I removing any surrounding quotes (")
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
那麼「%%~dpa%%i」是什麼意思呢?假設 .REP 檔案之一位於目錄命令是"C:\Reports folder\123-Chemistry-101.rep"
.
%%~dpa意味著檔案的磁碟機號碼和路徑減去周圍的引號,即C:\Reports folder\
.
%%我正如我上面提到的,將是從文件名中提取的文件夾名稱(兩個連字符分隔符之間的任何內容),因此在本例中Chemistry
.
把它們放在一起,「%%~dpa%%i」會將該檔案擴展為"C:\Reports folder\Chemistry"
,因為這是我們希望將檔案移至的位置。