Question

I would like to have a batch file wich will sort files by file type and sorts them into folder. For example I will run this batch file in some folder and .PDF files will be saved in "PDF" folder, same to do with other file types. Is possible to do that in command line? Thank you.

Was it helpful?

Solution

Please put the code below in a .bat file and save it to your folder with files and run it.

@echo off
rem For each file in your folder
for %%a in (".\*") do (
    rem check if the file has an extension and if it is not our script
    if "%%~xa" NEQ ""  if "%%~dpnxa" NEQ "%~dpnx0" (
        rem check if extension forlder exists, if not it is created
        if not exist "%%~xa" mkdir "%%~xa"
        rem Copy (or change to move) the file to directory
        copy "%%a" "%%~dpa%%~xa\"
    )
)

OTHER TIPS

Try this:

@echo off
setlocal enabledelayedexpansion

for %%a in (*.*) do (
   set "fol=%%~xa" & set "fol=!fol:.=!"
   if not exist !fol! md !fol!
      for /f %%b in ('dir /on /b *.*') do (
         if %%~xb EQU .!fol! move %%~nxb !fol!
      )
)
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET destdir=c:\destdir
SET "extdone=:"
FOR /f "delims=" %%a IN ('dir /b /a-d') DO (
 SET ext=%%~xa
 IF DEFINED ext (
  SET extdone|FIND /i ":%%~xa:" >NUL
  IF ERRORLEVEL 1 (
   SET extdone=:%%~xa: !extdone!
   IF EXIST "%destdir%\!ext:~1!" (
    ECHO MOVE "*%%~xa" "%destdir%\!ext:~1!"
   ) ELSE (ECHO no MOVE "%%~xa")
  )
 )
)
GOTO :EOF

This batch should do as you ask.

The required commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE to MOVE to actually move the files.

I've assumed that you only wish to move the files if destinationdirectory\extensionfound exists. If you want to create a directory for a new extension, simply add a line

md "%destdir%\!ext:~1!" 2>nul

after the SET extdone=:%%~xa: !extdone! line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top