Win7 Batch File - Moving Subfolders(& Files) to Grand-Parent Directory

122 views Asked by At

I have a somewhat complicated problem. I've downloaded an archived website from archive.org using Httrack and now I have thousands of subfolders and files I need to merge before I can rebuild it.

I'm trying to write a batch file to solve the problem. But my search results never come close to what I'm trying to achieve.

I'm trying to make these:

D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110202194232\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110202194331im_\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110202194449cs_\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110202194453im_\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110202194505cs_\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110101000000_\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110101072153\http_\www.site.com\*
D:\Utilities\httrack\SITES\RW\web.archive.org\web\20110201061410\http_\www.site.com\*

Into this:

D:\Utilities\httrack\SITES\RW\web.archive.org\web\http_\www.site.com\*

Basically trying to move "http_" into its grand-parent directory("web"), with it's subfolders and files. As if I were dragging and dropping, clicking "Yes" to Merge Folders, and clicking "Move, but keep both files".

I'd also like it to rename any files with the same name to avoid deletion.

IE:

web\http_\www.site.com\index.html
web\http_\www.site.com\index (1).html
web\http_\www.site.com\index (2).html

Thanks in advance for your help!!!

1

There are 1 answers

2
rojo On BEST ANSWER

Challenge: accepted. Wouldn't it be nice if this functionality were built into robocopy, xcopy, fso.CopyFile, PowerShell's Move-Item, or any other utility or scripting object method?

You probably ought to test this on a copy of the hierarchy. I did some minimal testing and it seemed to work as intended, but it will be destructive if there are unforeseen problems.

@echo off
setlocal

set "root=D:\Utilities\httrack\SITES\RW\web.archive.org\web\"

for /d %%I in ("%root%\2*") do (
    set /P "=Moving %%~nxI... "<NUL
    pushd "%%~fI"
    for /r %%J in (*) do (
        set "relative=%%~dpJ"
        setlocal enabledelayedexpansion
        call :mv "%%~fJ" "%root%!relative:%%~fI\=!"
        endlocal
    )
    popd
    rd /q /s "%%~fI"
    echo Complete.
)

goto :EOF

:mv <srcfile> <destdir>
setlocal disabledelayedexpansion
if not exist "%~f2" md "%~f2"
set /a seq = 1
set "filename=%~nx1"
:mv_loop
if exist "%~f2\%filename%" (
    set "filename=%~n1 (%seq%)%~x1"
    set /a seq += 1
    goto mv_loop
)
move "%~f1" "%~f2\%filename%" >NUL
endlocal & goto :EOF