I'm trying to remove a prefix of some directories.
I have many directories with names like '991234', '991235', '991236'. I want to remove the '99' from these folder names. The result needs to be a rename of the directories. They should be renamed to '1234', '1235', '1236'.
After some search I could write this script:
for /f "tokens=*" %%a in ('dir 99* /A:D /b') do ren "%%a" "00_%%a"
this script find all directories starting with '99' and call ren for each of them. The problem is that I could not remove the '99' part to apply in the folder name.
CodePudding user response:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:: I use a test directory name that includes spaces to verify that the routine works with such directorynames
:: Use SET "sourcedir=." for the current directory
SET "sourcedir=u:\your files\t w o"
for /f "tokens=*" %%a in ('dir /A:D /b "%sourcedir%\99*"') do SET "dirname=%%a"&ECHO ren "%sourcedir%\%%a" "!dirname:~2!"
GOTO :EOF
The metavariable %%a
needs to be assigned to a user variable for manipulation. Since the user variable will change value within the code block, delayedexpansion
needs to be invoked.
See for /?
and set /?
for documentation, as well as Stephan's DELAYEDEXPANSION link: https://stackoverflow.com/a/30284028/2128947
The required REN commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO REN
to REN
to actually rename the directories.
Always verify against a test directory before applying to real data.