Vivago
Vivago

Reputation: 11

Batch move folders from a subdirectory to another subdirectory that contains the same number

I have a folder structure and want to "merge" the folders. What I mean with that is: if a folder exists in b\ *\ and contains the number of a folder in p\ *\ move folder from b to p.

e.g. move b\p 11 - 20\11_abc into p\p_11_20\11

I currently have:

@Echo off

SETLOCAL ENABLEDELAYEDEXPANSION

cd /d "%~dp0"

for /f %%a IN ('dir /b "%~dp0\p\"') do (
    set "tmp=Y"
    for /f %%b IN ('dir /b "%~dp0\p\%%a\"') do if defined tmp (
        echo %%b
    )
    set "tmp="
)

which provides me with the numbers (e.g. 11, 12, 13, 21, 22, 23) Now I need a way to find out, if a folder in b\ *\ ... with that leading number exists. If yes it needs to be moved to the corresponding p\ *\ ... folder

Upvotes: 0

Views: 43

Answers (1)

Vivago
Vivago

Reputation: 11

I found a solution. It's not pretty and also not very fast, but it get's the job done.

What I basically did is to loop through every folder in \p. With the number of each folder I loop through every folder in \b. For every folder I find in \b\ I check if it begins with the number of the current \p\ folder; If yes, move the folder.

@Echo off

SETLOCAL ENABLEDELAYEDEXPANSION

cd /d "%~dp0"

for /f "delims=" %%a IN ('dir /b "%~dp0p\"') do (
    set "tmp1=Y"
    for /f "delims=" %%b IN ('dir /b "%~dp0p\%%a\"') do if defined tmp1 (
        set "tmp2=Y"
        for /f "delims=" %%c IN ('dir /b "%~dp0b\"') do if defined tmp2 (
            set "tmp3=Y"
            for /f "delims=" %%d IN ('dir /b "%~dp0b\%%c\"') do if defined tmp3 (
                set "tmpstr=%%d"
                set "tmpstr=!tmpstr:~0,2!"
                if "!tmpstr!"=="%%b" (
                    echo moving folder %%d to %%b ...>>log.txt
                    echo moving folder %%d to %%b ...
                    move "%~dp0b\%%c\%%d" "%~dp0p\%%a\%%b"
                )
                
            )
            set "tmp3="
        )
        set "tmp2="
    )
    set "tmp1="
)

Upvotes: 1

Related Questions