4

Simple example: (my problem is involving thousands of folders)

I have two folders with the names:

"A0000001_words_letters"

"A0000002_lots_of_numbers"

How would I automatically trim all folder names to just contain the AXXXXXXX start. This start will always be the same number of characters so effectively just keeping the first x characters of the name.

Thanks

Tim
  • 41

2 Answers2

1

You can use a FOR /F loop to set delimiters and tokens parsing folder name parts and use those to set variables for later use with the REN command.

You also want to utilize the Setlocal EnableDelayedExpansion to handle the expanding of the variables set in the loop accordingly to be properly used (not parsed at runtime) with the rename command per iteration within the loop.

@ECHO

SET srcdir=C:\folder\path
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "TOKENS=*" %%F IN ('DIR /B /AD "%srcdir%\*"') DO (
    SET fname=%%~F
    SET fname=!fname:~0,8!
    SET fname=!fname!
    REN "%srcdir%\%%~XNF" "!fname!"
)
EXIT

Further Resources

1

If there is always an _ after the first x characters, then the following will work from the command line (no batch needed)

for /d %A in (*) do @for /f "delims=_ eol=_" %B in ("%A") do ren "%A" "%B"

Double the percents if you put the above command within a batch script.

If you cannot rely on _ after the first x characters, then this command should work from the command line, preserving the fist 8 characters:

for /d %A in (*) do @set "folder=%A"&call ren "%^folder%" "%^folder:~0,8%"

Or you could use this batch scrip to preserve the first 8 characters:

@echo off
setlocal disableDelayedExpansion
for /d %%A in (*) do (
  set "folder=%%A"
  setlocal enableDelayedExpansion
  ren "!folder!" "!folder:~0,8!"
  endlocal
)

Or you could use my JREN.BAT regular expression renaming utility. It is pure script (hybrid batch/JScript) that runs natively on any Windows machine from XP onward - no 3rd party exe file required.

Remove everything from the first _ onward

jren "_.*" "" /d

Preserve the first 8 characters

jren "^(.{8}).*" "$1" /d

Note: If you were trying to rename files instead of folders, then you could do something like

ren *.txt ????????.txt

But unfortunately, you cannot use wildcards when renaming folders. So this technique is useless for folders. See How does the Windows RENAME command interpret wildcards? for more info.

dbenham
  • 11,794