0

I'm looking for a way to batch rename multiple folders. Basically, I need to pad it with leading zeros and make it a 6-digit

Example:

123 ---> 000123

22 ----> 000022

5678 --> 005678

The only way I know how to do it is:

for /f %f in ('dir /b') do ren "%f" "0%f"  but this only pads it with 1 zero

Please help. Any direction is appreciated Thanks

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Poe
  • 13
  • 3

1 Answers1

0

In a batch file can be used the following code:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /F "delims=" %%I in ('dir /AD-L /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /R /X "[0123456789][0123456789]*"') do (
    set "FolderName=00000%%I"
    set "FolderName=!FolderName:~-6!"
    if not !FolderName! == %%I ren %%I !FolderName!
)
endlocal

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • dir /?
  • echo /?
  • endlocal /?
  • findstr /?
  • for /?
  • if /?
  • ren /?
  • set /?
  • setlocal /?

Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with output filtered additionally by findstr with using a separate command process started in background with cmd.exe /c and the command line within ' appended as additional arguments.

Mofi
  • 46,139
  • 17
  • 80
  • 143