【问题标题】:Batch file - Loop directories and rename alphabetically批处理文件 - 循环目录并按字母顺序重命名
【发布时间】:2016-01-19 16:52:09
【问题描述】:

我正在尝试编写一个批处理脚本来查找所有目录和子目录,并将它们重命名为单个字母

这是我目前所拥有的

@echo off
SET "alfa=0abcdefghijklmnopqrstuvwxyz"
SET count=1
FOR /D /r %%G in ("*") DO (call :subroutine "%%G")
GOTO :eof

:subroutine
 echo %count%:%1
::Get the letter from %alfa% at the index %count%
::Rename the directory %1 to the single char letter retrieved in line above
 SET /a count+=1
IF %count%==26 (
 SET /a count=1
)
 GOTO :eof

文件夹重命名为什么无关紧要,只要它是 a) 只有一个字母 b) 同名的目录不存在于该目录中

注意:一个目录中的目录不应超过 26 个

感谢您的帮助

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    下面的解决方案假设目录名称只有一个字符,该字符是一个字母。如果不是这样,则必须插入额外的代码。

    @echo off
    setlocal EnableDelayedExpansion
    call :treeProcess
    goto :EOF
    
    
    :treeProcess
    set "alfa=0abcdefghijklmnopqrstuvwxyz"
    
    rem Create "name" array with directory names
    set "count=0"
    for /D %%d in (*) do (
       set "dir=%%d"
       rem If dir name have more than one letter
       if "!dir:~1!" neq "" (
          rem ... insert it in "name" array
          set /A count+=1
          set "name[!count!]=%%d"
       ) else (
          rem ... remove such letter from the alfa string
          set "alfa=!alfa:%%d=!"
       )
    )
    
    rem Rename the directories from "name" array to just one letter from alfa string
    for /L %%i in (1,1,%count%) do (
       ren "!name[%%i]!" "!alfa:~%%i,1!"
       set "name[%%i]="
    )
    
    rem Recursively call this subroutine to process nested directories
    for /D %%d in (*) do (
        cd %%d
        call :treeProcess
        cd ..
    )
    exit /b
    

    【讨论】:

      【解决方案2】:
      @ECHO OFF
      SETLOCAL 
      SET "targetdir=U:\sourcedir"
      SET "alphas=a b c d e f g h i j k l m n o p q r s t u v w x y z"
      :: prefix each dirname in the subtree with "#" to avoid name-clashes.
      FOR /f "delims=" %%t IN ('dir /s /b /ad "%targetdir%" ^|sort /r') DO REN "%%t" "#%%~nxt"
      :: Repeat scan and rename
      FOR /f "delims=" %%t IN ('dir /s /b /ad "%targetdir%" ^|sort /r') DO (
       SET "renamed="
       FOR %%r IN (%alphas%) DO IF NOT defined renamed IF NOT EXIST "%%~dpt%%r" REN "%%t" "%%r"&SET "renamed=%%r"
      )
      
      GOTO :EOF
      

      您需要更改targetdir 的设置以适应您的情况。

      首先,重命名子树 b 中的每个目录,并在其名称前加上一些与任何子目录名或文件名的开头都不匹配的字符串。这可以变得智能,但我只是使用了#

      通过sort倒序命名,任何子目录名称都会出现在其父目录之前,因此我们不会出现尝试重命名父目录已更改名称的子目录的情况。

      然后,使用相同的原则,尝试根据需要将子目录的名称更改为单字母,通过检查是否已经存在该级别的子目录与问题的字符。

      我建议对虚拟子树执行此操作以判断其适用性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-03
        • 2013-05-27
        • 2013-10-23
        • 1970-01-01
        • 2014-04-22
        • 1970-01-01
        • 1970-01-01
        • 2017-01-01
        相关资源
        最近更新 更多