2015-08-26 48 views
0

我有讀起來就像一個目錄結構:CMD.EXE批量裁剪目錄名稱

nnnnnn~substring 

n是數字和substring是字母。 我正在嘗試編寫一個批處理文件,用於測試目錄中是否存在特定的文件,如果存在,它應該將該目錄重命名爲substring。 批處理文件應該是這樣的:

for /f "tokens=\*" %%a in ('dir /b') do if exist filename (rename nnnnnn~substring substring) 

如何修剪所有的數字和目錄名的〜字符,所以我可以只使用名字的最後一部分改名? 〜分隔符之前的數字具有不同的長度,其後的子串也是如此。

+1

編輯問題並指定是什麼問題。 – wOxxOm

回答

2
@echo off 
    setlocal enableextensions disabledelayedexpansion 

    rem Change to the target folder 
    pushd "x:\somewhere" && (

     rem For each folder inside it matching the indicated pattern 
     rem  Uses a dir command to search only folders and a 
     rem  findstr filter to ensure only matching folders 
     for /f "delims=" %%a in (' 
      dir /ad /b *~* ^| findstr /r /c:"^[0-9][0-9]*~..*$" 
     ') do (

      rem Check if the folder contains the file 
      if exist "%%~fa\flagFile.txt" (

       rem Split the folder name using the ~ as delimiter 
       for /f "tokens=1,* delims=~" %%b in ("%%~na") do (

        rem Check that the new folder name does not exist 
        if not exist "%%~c%%~xa" (
         rem Execute the rename operation 
         echo ren "%%~fa" "%%~c%%~xa" 
        ) 
       ) 
      ) 
     ) 
     rem Restore previous active directory 
     popd 
    ) 

重命名操作只回應到控制檯。如果輸出是正確的,刪除​​前綴ren命令

0

這可能工作echo - 在你的文件夾結構的副本進行測試:
它假定substring在你的問題中不包含任何~字符。

@echo off 
:loop 
for /d /r "d:\base\folder" %%a in (*~*) do (
    if exist "%%a\filename" for /f "tokens=1,* delims=~" %%b in ("%%~nxa") do (
    ren "%%a" "%%c" 
    goto :loop 
) 
) 
pause 

這是僅爲當前目錄中的文件夾而設計的。

@echo off 
for /d %%a in (*~*) do (
    if exist "%%a\filename" for /f "tokens=1,* delims=~" %%b in ("%%~nxa") do ren "%%a" "%%c" 
) 
pause 
+0

如果您的文件夾結構不包含嵌套子目錄,則可以簡化此操作。 – foxidrive

+0

它做的工作,但然後循環重複錯誤「文件已存在或文件未找到」,我不得不停止它與Ctrl-C。順便說一句:沒有嵌套的目錄。 – Ignasi

+0

@Ignasi你用什麼名字來批處理文件?所有'substring'部分都是唯一的嗎? – foxidrive