I have a batch file that currently puts every file in a folder with the name of the file. However it only works for that folder I am in. I would like to have one batch file at the top of my directory that will only execute files 2 subfolders down. Example of directory:
/Parent folder **This is where I want my batch file**
/Subfolder 1
/Subfolder 1A/file.jpg **Level I want batch file to execute**
/Subfolder 1B/file.mp4 **Level I want batch file to execute**
/Subfolder 1C/file.mp3 **Level I want batch file to execute**
/Subfolder 2
/Subfolder 2A/file.jpg **Level I want batch file to execute**
/Subfolder 2B/file.mp4 **Level I want batch file to execute**
/Subfolder 2C/file.mp3 **Level I want batch file to execute**
This is my current batch file:
@echo off
for %%a in (*.*) do (
md "%%~na" 2>nul
move "%%a" "%%~na"
)
Use a FOR loop with the /D option to iterate folders, repeating for as many levels as necessary. Use PUSHD at each step so that you don't have to keep track of the full path.
@echo off
for /d %%a in (*) do (
pushd "%%a"
for /d %%b in (*) do (
pushd "%%b"
for %%c in (*) do (
md "%%~nc" 2>nul
move "%%c" "%%~nc"
)
popd
)
popd
)
You can use %~dp0
to guarantee you start at the parent folder of the batch script:
@echo off
for /d %%a in ("%~dp0*") do (
pushd "%%a"
for /d %%b in (*) do (
pushd "%%b"
for %%c in (*) do (
md "%%~nc" 2>nul
move "%%c" "%%~nc"
)
popd
)
popd
)
The code becomes tedious as you add more levels. You can use recursion to write more generic code that can easily be changed to work at any subfolder depth. Simply change the depth value as needed. Note how you can re-use letters within nested FOR loops.
@echo off
setlocal disableDelayedExpansion
set depth=2
:iterateFolders
setlocal
set /a depth-=1
for /d %%F in (*) do (
pushd "%%F"
if %depth% gtr 0 (
call :iterateFolders
) else for %%F in (*) do (
md "%%~nF" 2>nul
move "%%F" "%%~nF"
)
popd
)
exit /b
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments