0

I was looking at this as reference: batch file Copy files with certain extensions from multiple directories into one directory

I have about 300k+ files contained in [sub]folders with many file types that need to be moved to folders based on their file extension. I need help forming the cmd to place files in respective folders based on extension.

Simi-Pseudo code:

for /R C:\Recovery %f.%EXT move %f C:\RecoverySorted\%EXT

The code above doesn't work properly of course. Need help revising.

If there could be error checks for non-extension files that would be great as well. I noticed a few files without extensions. Thanks!

Community
  • 1
  • 1
kisk
  • 113
  • 1
  • 6

2 Answers2

2
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%i IN ('dir /s /b /a-d') DO (
 IF NOT "%%~xi"=="" MD "c:\destdir\%%~xi" 2>NUL
 ECHO MOVE "%%i" "c:\destdir\%%~xi"
)

Include your source directory name in the dir clause if you are not starting in the desired relative root. Change destdir to suit. The 2>nul suppresses error messages on the make-directory because this will attempt to make the directory .ext many times. Add >nul to the MOVE... line to suppress the move-report. delete the echo on that line to actually perform the move rather than reporting the move to be made. Test on a small sub-tree first.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • 1
    I'd prefer `for /R "C:\Recovery" %%i in (*) do ...` over a `dir`-based solution. Also I'd use `"%%~i"` instead of `"%%i"`, just to be on the safe side. – Ansgar Wiechers Apr 22 '13 at 16:50
  • Yes, I also prefer this form. `for /F ... in ('dir...` requires to execute a copy of cmd.exe and create a temporary file, whereas `for /R ... in (*)` is immediate and execute faster. – Aacini Apr 22 '13 at 20:19
  • sure, filtering dir is not the way for 300k files. – ElektroStudios Apr 23 '13 at 00:33
2
@Echo OFF

Set "Folder=C:\windows"
Set "DestDir=C:\MySortedFiles"

FOR /R "%Folder%" %%# in ("*") DO (
    If not exist "%DestDir%\%%~x#" (MKDIR "%DestDir%\%%~x#")
    Echo [+] Moving: "%%~nx#"
    Move "%%#" "%DestDir%\%%~x#\" 1>NUL
)

Pause&Exit

Note: Don't use a last slash \ when typying the DestDir path.

ElektroStudios
  • 19,105
  • 33
  • 200
  • 417