menu

Questions & Answers

How can I remove a specific part of many folders names using .bat files?

My university is using a proprietary system that outputs data in a very specific way in which each "module" is output into folders following the structure (4 digit numeral) - (name of module)

ex: 5574-CHEM104

I need to remove the name and hyphen so that only the numeral remains: 5574-CHEM104 > 5574

The problem is that there's thousands of these folders and there's no way I could do it by hand. I'm having difficulty trying to automate the process, so if anyone could at least point out a command I could look into it would help immensely

I've tried the REN command, putting "REN 5574-CHEM104 5574", but it only works for one folder. There's thousands of folders, each with different numerals, under "CHEM104", for example, and I need for the program to rename the folder no matter the original name into the first 4 original numerals, which I can't figure out. Thanks!

Comments:
2023-01-23 00:00:03
If the numeric part always consists of four figures, use ren "????-*" "????"; otherwise, use for /F "tokens=1-2 delims=-" %%I in ('dir /B /A:D-H-S "*-*"') do ren "%%I-%%J" "%%I"
Answers(1) :
@ECHO OFF
SETLOCAL
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
FOR /f "delims=" %%e IN (
 'dir /b /ad "%sourcedir%\*" '
 ) DO FOR /f "delims=-" %%o IN ("%%e") DO ECHO REN "%sourcedir%\%%e" "%%o"
)

GOTO :EOF

Always verify against a test directory before applying to real data.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the directories.

Using a list of the directory-names, names only (/b) and directories only (/ad), tokenise the name using - as a delimiter and execute the rename using the token assigned to %%o (default is first token)