0

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!

ixcode
  • 611
  • 8
  • 17

1 Answers1

1

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"
K J
  • 8,045
  • 3
  • 14
  • 36
  • First, thanks a lot for taking the time to write such a helpful answer! It worked exactly how I need it to be. Although one problem that I knew would happen is that it created several repetitive folders for each file (at least 8 levels (folders) for the same file). Do you know if it's possible to prevent creating duplicate folders? If not, it's alright, you're still very helpful! Thank you! – ixcode Oct 12 '21 at 00:27
  • I guessed there would be "wrinkles" such as needing exclusions, but cant guess how unseen data (filenames) cause duplication so how does your 8 for 1 come about ? – K J Oct 12 '21 at 00:30