批处理脚本以递归方式重命名具有父文件夹名称的文件和文件夹,并添加前缀/后缀

时间:2015-09-14 17:42:34

标签: windows batch-file command-line

我有2个文件夹,fol1fol2

fol1
  ├───fol1.1
  │   └───text.txt
  ├───fol1.2
  │   └───text.txt
fol2
  ├───fol2.1
  └───fol2.2

我想将树重命名为:

lon_fol1_par
  ├───lon_fol1.1_par
  │   └───fol1.1_text.txt
  ├───lon_fol1.2_par
  │   └───fol1.2_text.txt
lon_fol2_par
  ├───lon_fol2.1_par
  └───lon_fol2.2_par

帮助我重命名的代码如下:

FOR /F "tokens=1 delims=" %%A IN ('DIR /B /S /A:D') DO (

   FOR /F "tokens=1 delims=" %%B IN ('DIR /B /A:-D "%%A"') DO (
    pushd %%A
    FOR %%I IN (.) DO RENAME "%%A\%%B" "<Name I want>"%%~xB
    popd ..
  )   
)  

1 个答案:

答案 0 :(得分:1)

在向文件夹名称

添加前缀和后缀之前,首先重命名文件

请注意:此脚本意味着没有排除目录重命名过程,该过程仅限于:包含文件的文件夹 text.txt

如果是这样,你必须做一些不在那个剧本中的事情。

注意:echo命令前删除rename命令以使其处于活动状态。 您还可以在PAUSE命令之后添加rename命令,以查看发生的情况

@echo off
REM Renaming files first before adding a prefix and a suffix to the folder names

REM Be aware: This script implies that there have not excluded directories...
REM ...renaming process that would only condition: the folder containing the files text.txt
REM If so, you have to do something else that are not in that script.

REM Note: Remove echo command in front of rename command to make it active.

setlocal enabledelayedexpansion
FOR /F "tokens=* delims=" %%F in ('dir /s /b /a-d text.txt') DO (
    set "DIRPATH=%%~dpF"
    set "FILEPATH=%%~F"
    set "FILENAME=%%~nxF"
    IF "!DIRPATH:~-1!" EQU "\" (
        SET "DIRPATH=!DIRPATH:~0,-1!"
    )

    FOR %%G IN ("!DIRPATH!") DO (
        set "PICDIR=%%~nxG"
        echo:
        echo   renaming files
        echo   rename "!FILEPATH!" "!DIRPATH!\!PICDIR!_!FILENAME!"
    )
)
endlocal
REM Then renaming folders with prefix and suffix
set "prefix_=lon_"
set "_suffix=_par"
FOR /F "tokens=* delims=" %%D in ('dir /s /b /ad') do (
    echo   renaming folders
    echo   rename "%%~D" "%prefix_%%%~nD%_suffix%"
)

EXIT /B 0