我正在嘗試制作一個批處理腳本來根據另一個目錄中的匹配名稱重命名檔案串列。我對此的思考程序是這樣的:
注意事項
- 目錄 1 和 2 中的檔案具有相同的名稱
- 目錄 2 和 3 中的檔案具有相同的檔案大小
- 目前腳本似乎什么都不做,檔案沒有改變
- 遍歷目錄 3 中的所有檔案并按大小分配給陣列
- 遍歷目錄 2 中的所有檔案并按大小分配給陣列
- 將目錄 1 中的名稱與目錄 2 進行比較,并將匹配的檔案重命名為目錄 3 中的檔案
這是我能夠想出的(我對批處理很不熟悉,所以請原諒我):
@Echo off
setlocal enableextensions enabledelayedexpansion
set /a i = 0
set /a j = 0
set /a k = 0
set /a l = 0
for /f "delims=" %%f in ('dir "PATHtoDirectory3*extension" /o:s /b') do (
set d3[%i%] = %%f
set /a i = 1
)
for /f "delims=" %%g in ('dir "PATHtoDirectory2*extension" /o:s /b') do (
set d2[%j%] = %%g
set /a j = 1
)
for /f "delims=" %%h in ('dir "PATHtoDirectory1*extension" /o:s /b') do (
set d1[%l%] = %%h
for /l %%x in (1,1,100) do (
if !d1[%l%]! == !d2[%k%]! (ren !d1[%l%]! !d3[%k%]!) else (set /a k = 1)
)
set /a l = 1
)
endlocal
uj5u.com熱心網友回復:
一個例子會很好。
假設我們在 3 個目錄中都有(檔案名大小):
dir1 dir2 dir3
c 1 b 6 w 6
d 2 c 7 x 7
a 3 a 8 y 8
b 4 d 9 z 9
我收集的任務是將 dir1 中的 c 重命名為 x、d、za、yb、w。
所以 - 對于您的代碼(請使用描述性名稱 - 一個字母的名稱很難遵循,并且可能會與您的代碼中的metavariables類似名稱混淆)%%x
for /f "delims=" %%f in ('dir "PATHtoDirectory3*extension" /o:s /b /a-d') do (
set /a i = 1
set "d3[!i!]=%%f"
)
添加/a-d開關以防止dir報告目錄名稱(“良好做法”,即使您確定(目前)不會有子目錄)
增加索引,然后存盤資料。這意味著您正在處理 d3[1..count] 而不是 d3[0..count-1]。這將使生活更輕松。
洗掉 周圍的空格,=因為這些空格將分配給變數名和存盤在字串賦值中的值。“參考陳述句”以確保將行上的任何雜散尾隨空格分配給該值。
您需要修改后的索引值;!var!是修改后%var%的值,是遇到陳述句時的值(即決議時)
重復所有 3 個回圈。
注意i,j和l現在每個都應該包含遇到的檔案名的數量。據推測,這些應該是相同的。
下一個問題是,如果 d3 中的檔案名與 d1 中的任何檔案名相同,那么您可能會嘗試重命名d1\xyz為已存在abc的檔案名。d1\abc
將%%x回圈從它所在的位置移動到構建陣列之后。d1
請注意,您有i,j和中的名稱計數l,因此您可以使用
for /L %%x in (1,1,%i%) do ...
要遍歷陣列,您不需要使用任意數字。您可以嵌套for陳述句:
for /L %%x in (1,1,%i%) do for /L %%y in (1,1,%i%) do ...
現在您可以簡單地使用比較 d1,d2 名稱
if "d1[%%x]"=="d2[%%y]"
如果這是真的,那么 d3[%%y] 包含新名稱。
要實作這一點,請嘗試
pushd PATHtoDirectory1
md tempdirname
for /L %%x in (1,1,%i%) do for /L %%y in (1,1,%i%) do if "d1[%%x]"=="d2[%%y]" (
move d1[%%x] .\tempname\d3[%%y]
)
move .\tempdirname\* .
rd tempdirname
popd
Where the pushd switches the current directory to PATHtoDirectory1; create a temporary directory there;match each name and move the file to the new name in the subdirectory;move the files with their new names back to the main directory;remove the subdirectory and popd returns to the original directory from which the batch is run.
Since the names in dir3 are unique, so the subdirectory will have unique names, and the rename to same or existing name problem is eliminated.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/439568.html
