【问题标题】:Batch script to recursively rename files and folders递归重命名文件和文件夹的批处理脚本
【发布时间】:2015-09-14 17:42:33
【问题描述】:

我需要一个 Windows 批处理脚本来递归地使用父文件夹的名称重命名文件和文件夹并添加前缀/后缀。

我有 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 ..
  )   
)  

【问题讨论】:

  • 是的,有可能;你试过什么了?请记住,SO 不是编码服务...
  • 文件夹中是否只有 .txt 文件?
  • 是的@aschipfl,我尝试了一些东西。 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" "%array[1]%_%%~nB_%%~ nI_%array[2]%_%array[3]%%%~xB" popd .. ) )
  • 抱歉……我是新手。请设法仔细阅读@aschipfl。谢谢:)

标签: windows batch-file command-line


【解决方案1】:

在为文件夹名称添加前缀和后缀之前先重命名文件

注意:此脚本暗示没有排除目录重命名过程,仅条件是:包含文件的文件夹 text.txt

如果是这样,您必须执行该脚本中没有的其他操作。

注意:删除echo 命令前面的rename 命令以使其处于活动状态。 您也可以在rename 命令之后添加PAUSE 命令一行,看看会发生什么

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多