Home > other >  How to auto create folder based on filename and move the file into it's folder using .BAT
How to auto create folder based on filename and move the file into it's folder using .BAT

Time:10-12

I have already solved my question... What I haven't solved is how to do this if the .bat file is located in a parent folder and that it should work on all subfolders?

Right now, there's a limitation that it only create folders if the .bat file is located in the same folder as the files. It can't create folders if the files are inside a subfolder.

What I have is:

the filename of this .bat is :

organize.bat

@echo off
for %%i in (*) do (
 if not "%%~ni" == "organize" (
  md "%%~ni" && move "%%~i" "%%~ni"
 )
)

How I do it right now:

  1. I place the .bat file in a folder together with the files
  2. When I click it, it will create folders with a name based on the files inside that folder
  3. It will also move each files in those folders of the same name

What I need:

  1. Place the .bat file in the main folder with many subfolders containing the files
  2. Click it to perform the same tasks above

Apologies if my explanation is confusing... I hope it's still understandable.

Thank you in advance!

CodePudding user response:

Your attempt is very close to working but beware the wrinkles of using a simple approach without checking each detail so, start here:-

@echo off & Title %~n0
REM I recommend using cd /d "%~dp0" to ensure you start from the known cmd file folder location not some system folder
cd /D "%~dp0"
REM add the /R switch to run through subdirs
for /R %%i in (*) do (
REM replace organize to %~n0 so as to aid renaming by other users
 if not "%%~DPni" == "%~DPn0" (
REM to allow for nested paths we need a fuller DP location for N (check it works exactly as desired then remove the echos)
  echo md "%%~DPni" && echo move "%%~i" "%%~DPni"
 )
)

BEWARE files with double .dot.s such as cmd.exe.lnk so check those echo's first

md "C:\Users\me\Favorites\Links\cmd.exe"
move "C:\Users\me\Favorites\Links\cmd.exe.lnk" "C:\Users\me\Favorites\Links\cmd.exe"
  • Related