我認為我非常接近。我有一個檔案夾,我試圖在其中重命名所有子檔案夾和檔案,以便去除大寫字母,將符號替換為適用的單詞,并將檔案及其父子檔案夾中的空格更改為連字符。
這是我到目前為止的批處理檔案:
cd d:\scripts\testing\
for /r %%D in (.) do @for /f "eol=: delims=" %%F in ('dir /l/b "%%D"') do @ren "%%D\%%F" "%%F"
SET location=d:\scripts\testing\
for /R %location% %%A in (*.*) do call :replspace "%%A"
for /R %location% %%A in (*.*) do call :repland "%%A"
goto :eof
:replspace
set "_fn=%~nx1"
ren %1 "%_fn: =-%"
:repland
set "_fn=%~nx1"
ren %1 "%_fn:&=and%"
您可能會看到,首先它會遍歷并將 d:\scripts\testing\ 中的所有內容(檔案和檔案夾)重命名為小寫。接下來,它重命名同一目錄中的所有檔案,用連字符替換空格,用單詞“and”替換“&”。這一切都有效......除了我需要對檔案夾進行相同的符號和空間更改,而且我沒有找到任何關于如何做到這一點的真實資訊。
有人有什么建議嗎?
順便說一句,這在服務器 2012 r2 上運行,但是對于互操作性問題,腳本必須是老式的批處理腳本。
uj5u.com熱心網友回復:
您可以使用一個 for 回圈執行整個替換任務,使用dir /s遞回搜索目錄。
@echo off
setlocal enabledelayedexpansion
pushd "d:\scripts\testing\" || goto :EOF
for /f "delims=" %%i in ('dir /b /l /s') do (
set "item=%%~i"
set "item=!item:%%~dpi=!"
set "item=!item: =-!"
ren "%%~fi" "!item:&=and!"
)
popd
我沒有set將&替換作為變數,因為只完成了兩次替換,因此只需在最后一項上使用替換即可,無需set再次替換。如果您有更多替換要添加,請在該ren行之前添加它們:
請注意,此示例僅echo將結果用于測驗目的。echo只有在您確信結果符合預期時才洗掉。
然后,注意|| goto :EOF在pushd宣告中。這是有充分理由的關鍵。如果它失敗cd或pushd,通常腳本將繼續重命名,從它開始的作業目錄,或者以前的cd pushd等等。在這種情況下,如果它找不到目錄,或者它沒有權限,它會完全跳過腳本的其余部分。
最后注。如果您的檔案或檔案夾包含!這將需要更改。然后,您可以簡單地恢復將setand移動ren到標簽,然后呼叫標簽,因為這delayedexpansion將導致!丟失。
uj5u.com熱心網友回復:
雖然 Gerhard 的腳本很干凈并且應該可以作業,但它在某些情況下(例如我的情況)會自行跳閘。我最終使用了這個腳本:
rem #### Step 1: move to working directory ####
cd "d:\scripts\testing\"
rem #### Step 2: change case on everything ####
for /r %%D in (.) do @for /f "eol=: delims=" %%F in ('dir /l/b "%%D"') do @ren "%%D\%%F" "%%F"
rem #### Step 3: set location ####
SET location=d:\scripts\testing\
for /R %location% %%A in (*.*) do call :replspace "%%A"
for /R %location% %%A in (*.*) do call :repland "%%A"
rem #### Step 4: replace spaces/symbols on directories ####
setlocal enabledelayedexpansion
pushd "D:\scripts\testing\" || goto :EOF
for /f "delims=" %%i in ('dir /l /b /s /ad') do (
set "item=%%~i"
set "item=!item: =-!"
move "%%~fi" "!item:&=and!"
)
popd
rem #### variables ####
:replspace
set "_fn=%~nx1"
ren %1 "%_fn: =-%"
:repland
set "_fn=%~nx1"
ren %1 "%_fn:&=and%"
它結合了我自己的腳本和對 Gerhard 腳本的輕微修改。基本上,我最終逐步完成了修改。
- 將所有內容更改為小寫。
- 替換檔案名中的空格和符號。
- 替換目錄名稱中的空格和符號。
我知道這是重復的,我想用更少的線條來做,但它有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/473711.html
標籤:批处理文件
