简体   繁体   中英

Windows batch copy to sort folders into folders based on partial name

I have a directory full of folders beginning with 5-digit numbers:

\12611_Ants
\12866_Boats
\13898_Cats
\13898B_Misbehaving_Cats

I would like a batch script which will create (if necessary) folders in order to sort these folders in groups of 100, so in this example, \12600, \12800, and \13800 would be created, and:

\12611_Ants -> \12600
\12866_Boats -> \12800
\13898_Cats -> \13800
\13898B_Misbehaving_Cats -> \13800

Leaving me with:

\12600
\12800
\13800

At a later date, I may then have:

\12600
\12800
\13800
\12825_Bats
\14055_Pangolins

And I would want it to leave \12600, \12800, and \13800 alone, sorting only the \12825_Bats and \14055_Pangolins folders:

\12825_Bats -> \12800
\14055_Pangolins -> \14000

I am getting hung up on selecting the correct sorting folder based on the five digit number.

I do not usually post answers to off topic code requests, but there are too many individual parts to try to explain or link within the comment section. Here therefore is a quick example to assist you, which I will not be explaining further.

It uses the dir command to get your directory names which include an underscore, and the findstr utility to confirm that their names begin with exactly five numbers. Once it has the information it needs it uses the Robocopy utility to move the directories into their respective sorted parents.

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
If /I Not "%__CD__%" == "%~dp0" CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir *_* /B /A:D
 ^| %SystemRoot%\System32\findstr.exe
 "^[0123456789][0123456789][0123456789][0123456789][0123456789][^0123456789]*_"
 ') Do (Set "DName=%%G" & SetLocal EnableDelayedExpansion
    %SystemRoot%\System32\Robocopy.exe "%%G" "!DName:~0,3!00\%%G" /E /Move 1>NUL
    EndLocal)

The batch file should be placed in the same location as your directories.

To learn how each of the used commands work, please open a Command Prompt window, and enter the following, pressing ENTER after each:

  • echo /? ,
  • setlocal /? ,
  • if /? ,
  • cd /? ,
  • dir /? ,
  • findstr /? ,
  • for /? ,
  • set /? ,
  • robocopy /? .

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