简体   繁体   中英

Windows batch script to remove dashes from subfolders and the files within subfolders

I have a folder full of subfolders with filenames which occasionally have dashes as the sixth character. These subfolders will contain files with finames which also have dashes as the sixth character. I need to remove all of those dashes in the filenames of both the subfolders and their files.

I have studied and modified some code for my purpose, but the script is changing the subfolder name first, which breaks the script as it attempts to change the filenames within the now-renamed subfolder.

Can someone point me in the direction of a solution?

setlocal disableDelayedExpansion
for /f "delims=" %%F in ('dir /b /s ?????-*.*') do (
  set "old=%%F"
  set "new=%%~nF"
  setlocal enableDelayedExpansion
  ren "!old!" "!new:-=!"
  endlocal
)

The problem with your current code is that the renaming of directories start from root, so if a rename was done, the next level folder / file is not found, because it's parent is now renamed an error. For that reason, run a for loop on the files first by excluding directories /ad then use for /D instead with the /R ecursive switch to rename the folders:

@echo off
for /f "delims=" %%F in ('dir /b /a-d /s "?????-*.*"') do call :process "%%~F"
for /D /R %%F in (?????-*.*) do call :process "%%~F"
goto :eof

:process
set "name=%~nx1"
ren "%~1" "%name:-=%"

Result

dir s and Files before:

在此处输入图像描述

and After:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM