windows batch command to move all wanted sub-folders recrusively in a directory to a NEW folder - windows

I have a local Folder-A which have many subfolders (svn-repository), these subfolders both have a subfolder named .svn. Now I want to move all .svn folders to Folder-B, but incase of oneday I wants the .svn folders back to their original place so I can SVN update them, so the ".svn" folder's parent folder info must be exits in Folder-B
starts like this:
Folder-A
|_DR1
|_.svn
|_s1
|_.svn
|_s1_s1folder
|_.svn
|_file1
|_file1
|_s2
|_.svn
|_file1
|_file2
|_DR2 ... etc
Desired MOVE result:
Folder-A only have actual sub-folders and data but without .svn folder
Folder-B
|_DR1
|_.svn
|_s1
|_s1_s1folder
|_.svn
|_.svn
|_s2
|_.svn
|_DR2 ... etc
Desired RESTORE result:
Folder-A & Folder-B back to where we starts.
please help write commandlines to accomplish the MOVE and RESTORE mission, thank you

#ECHO OFF
SETLOCAL
:: establish source and destination directorynames; ensure dest exists
SET source=c:\folder-a
SET dest=u:\folder-b
MD %dest% 2>NUL
:: delete a tempfile if it exists
DEL "%temp%\svntmp2.tmp" 2>nul
:: create a dummy directory
MD c:\dummy
:: go to root of tree containing SVN directories
PUSHD "%source%"
XCOPY /L /s . c:\dummy |find /i "\svn\" >"%temp%\svntmp1.tmp"
POPD
:: goto destination directory
PUSHD "%dest%"
FOR /f "delims=" %%i IN ('type "%temp%\svntmp1.tmp"') DO CALL :moveit "%%i"
FOR /f "delims=" %%i IN (
'TYPE "%temp%\svntmp2.tmp"^|sort /r'
) DO RD "%%i" /S /Q
POPD
:: delete tempfiles
del "%temp%\svntmp1.tmp"
del "%temp%\svntmp2.tmp"
:: delete the dummy directory
RD /s /q c:\dummy
GOTO :eof
:moveit
:: get filename, remove quotes, then remove leading '.'
SET sourcefile=%~1
SET sourcefile=%sourcefile:~1%
FOR %%i IN ("%sourcefile%") DO (
MD ".%%~pi" 2>nul
MOVE "%source%%%~i" ".%%~pnxi"
>>"%temp%\svntmp2.tmp" ECHO %source%%%~pi
)
GOTO :eof
Set your source and destination directories.
Make a dummy empty directory
go to your source and generate a list of the files to be moved using
XCOPY/L and filtering for lines containing \svn\
go to your destination directory
move each file
remove the leading '.' from the XCOPY output
create the destination subdirectory; ignore 'it already exists' errors
move the file
record the directory name in a second tempfile
Sort the second tempfile in reverse, which puts the deepest subdirectories first
remove the directories, ignoring 'it is not there' errors
delete the tempfiles and dummy directory.
Note that the commands to actually DO the moves/directory creation/deletion are merely ECHOed. This is so that you can verify that the routine does what you want it to do. You would need to verify that it's correct, then remove the ECHO keyword from the statements to actually ACTIVATE the move. Test against a small dummy area first for safety's sake.
As for restoring - it's relatively easy.
xcopy /s/e/v "...folder-b\dr1\svn\" "\folder-a\dr1\svn\"
should do what you want, keeping the restored projects files in folder-b (delete if you like - it's your system) and you can restore on a project-by-project basis.
(I've used SVN throughout because the dot is getting a little small for me nowadays...)

Related

How to search/delete multiple subfolders?

I have a "clean up" batch program that sits in a parent directory & deletes certain extraneous files within the directory "tree".
One function is to delete extra ".backup" save folders (just .backup, not main folders)
For reference, the folder path is like:
\Parent folder (w/ my .bat)
\Saves
\save 1\save files
\save 1.backup\save files
\save 2\save files
\save 2.backup\save files
(etc)
I can remove the unwanted subfolders using
for /d %%x in (Saves\*.backup) do rd /s /q "%%x"
However, I want to add a check into the code to verify that the folders have actually been deleted & give correct message for success, failure, no folder, etc. outcomes.
I can do that with file deletion functions using IF EXIST/IF NOT EXIST arguments, but I'm having trouble applying these to the subfolder deletion.
I can look for files in the save folders to satisfy the EXIST/NOT EXIST arguments, but using the * wildcard in the subfolder name seems to be throwing a wrench into the works, and the program fails to detect any folders/files using that statement. However if I define a specific save folder outright, the subroutine will work perfectly.
So:
if not exist "Saves\save 1.backup\*.*" ( goto nofile )
if exist "Saves\save 1.backup\*.*" ( for /d %%x in (Saves\*.backup) do rd /s /q "%%x" )
will delete the correct folders (or give a message if no valid folders), but
if not exist "Saves\*.backup\*.*" ( goto nofile )
if exist "Saves\*.backup\*.*" ( for /d %%x in (Saves\*.backup) do rd /s /q "%%x" )
doesn't delete anything, & just gives my "nofile" message.
Obviously, specifying every possible save name isn't an option.
Any solutions?
p.s. to head off any extra questions: I want to [occasionally] delete these backups because the program makes a new one each time it saves.
You can check folder into for loop after command rd.
for /d %%x in (Saves\*.backup) do (
rd /q /s %%x
if exist %%x (echo Failed) else echo Success
)

Moving files from more than one folder to the parent directory using CMD

I have a folder Target contains multiple folders,
each folder contains one file with the same name of the folder
I want to move the files in folders Part1,Part2,Part3,Part4 and Part5
to parent folder ("Target" in this case) using cmd then delete the folders.
The result should be like that :
In Linux i could've used mv Part*\*.* ..
I've tried copy "Part*\*" "" command,
but it doesn't work.
Use a For loop. The key to getting directory names in this code is "dir /a:d" which only lists directories. I put that into the %%a variable. Use %~dp0 to refer to the directory the batch file is in. If your bat is somewhere else, do a find and replace all for that to the directory path you need. Lastly use RMDIR to remove each folder with /q /s to make it silent and remove all files within the directory (part1 part2 etc...) and the directories themselves.
#echo off
for /f "tokens=* delims=" %%a in ('dir /a:d /b "%~dp0"') do (
copy "%~dp0%%a\*.*" "%~dp0"
RMDIR /q /s "%~dp0%%a"
)
In the Windows Command Prompt, copy "Part*\*" "" cannot work, because wildcards are only permitted in the last element of a path but not somewhere in the middle.
To work around this, use a for /D loop to resolve wildcards in Part*, then let copy deal with the remaining ones:
for /D %I in ("Part*") do #copy "%~I\*" ".."
To move the files rather than to copy, simply replace copy by move. If you want to remove empty sub-directories then, append rd using &&:
for /D %I in ("Part*") do #move "%~I\*" ".." && #rd "%~I"
To use the above code fragments in a batch-file, ensure to double all the %-signs.

Move specific files out of subfolders and delete said subfolders

I recently exported the HDD on my panasonic camera to my notebook and noticed that the video files weren't ordered by name, but by their parent directory and said parent directory was clouded with a bunch of miscellaneous files.
To put things into perspective, the directory tree looks something like this:
\Panasonic
\PRG00A
\PRG00B
...
\PRG069
Panasonic is located inside a bunch of folders, hence why I would like to put my batch file alongside \Panasonic. And have it work relatively to its location.
So basically I want to create a batch file move.bat, which shall traverse the subdirectories of \Panasonic and move out any video files (with extension .MOD to simplify things) and afterwards delete the parent directory (e.g. \PRG00B).
The result would be that the \Panasonic directory only includes video files instead of sub-directories with a bunch of rubbish.
What I've got so far (keep in mind that this is my first batch script, and I haven't even tested it fully). The choice to continue doesn't work, by the way. Not sure why, though.
#echo off
cls
set dirName=%~dp0Panasonic
goto question
:start
goto move
goto end
:move
for /D %%G in ("%cd%") do (
for %%I in ("%%G") do (
if %%I equ "*.MOD" (
move /Y %%I %dirName%
)
)
rmdir /s /q %%G
)
:end
echo Done.
pause
endlocal
exit
:question
set /P c="Are you sure you want to proceed with moving video files from %dirName%? [Y/N]"
if /I %c% equ 'y' (
echo Moving files...
goto start
) else (
goto end
)
Once again, this is my first time creating a batch file, so any help is much appreciated!
you are almost there, but just need to fix a couple of things, very easy to fix, in fact, you just need to simplify a lot your code.
Just in three simple steps
Step 1. To loop over all the directories you already had it right, your friend is for /d
for /d %%a in (*) do echo %%a
Step 2. To move all the .mod files in each of the directories found, to its parent directory or one directory up in the hierarchy, that happens to be the current directory, you just need to
move %%a\*.mod .
don't use /y option, so it will not overwrite existing files already moved to the parent directory (You will have the opportunity the check the results later. Keep reading)
Step 3. And finally, remove the directory,
rd %%a
but don't use /s, so it will only work it the directory is empty, that is, if you have successfully moved out all of the files it contained. This way you can then browse thru them to see what is left without losing any data.
So, your moveupallmod.bat becomes simply
#echo off
for /d %%a in (*) do (
move "%%a\*.mod" .
rd "%%a"
)
and that's all!

copy paste files using CMD

I want to accomplish the following: copy File A from Directory A to Directory B but File A already exist in Directory B and i don't want to overwrite it, simply put the new file in Directory B with a (1) or something so i'll know the difference. i can't manually name the file in the script as i plan to make it a batch file and run it every few hours therefore resulting in the same file existing with different names. IE. File A, File A(1), File A(2) so on and so on. please help. Thank you
Use Xcopy command with parameter /D
C:\> xcopy D:\source_dest E:\target_dest /E /D
/E parameter make that it copy files with subfolders
/D parameter make that it copy files without overwrite
if want more help inform me .if it works vote up
A cyclic copy refers to the situation where the source directory
contains the destination directory. Since the destination directory
is part of the source, the copying process eventually starts copying
the destination directory to a deeper portion of the destination.
This process will continue until, of course, the finite disk space
eventually runs out.
To avoid this condition but to achieve the objective, one can
specify a temporary destination which is on another volume (e.g.,
D:\temp\) and later copy the temporary destination to the final
destination, and delete the temporary directory at the end.
just check file exist before run xcopy command then run copy command
if NOT EXIST c:\directory B\File A ( xcopy c:\Directory A\File A c:\Directory B )
The following is made for folders but you can modify it for files.
Makes a backup of existed folder directory (and all contents in it) with new increase number in folder name [like TEST(1)... TEST(2)... folder].
The first part :Start will set the %PathFolder% variable with path to folder name (%userprofile%\Desktop\TEST) and then will search if exist. If NOT exists, will create it (xcopy), else, If exist, will directing the %PathFolder% variable to :Search label (for-)loop section for further handling...
Tip: Can be used %1 variable to set PathFolder set "PathFolder=%1" so it will work when you Drag-n-Drop a folder on this current saved batch file.
The second part :Search will search in the %PathFolder% variable (%userprofile%\Desktop\TEST) and will make a COPY of "TEST" folder (and all contents in it) with an increase number added in parenthesis at the end of folder name [like TEST(1)]. If already exist TEST(1) then will copy TEST folder as TEST(2) ... or TEST(3) ... and so on.
::Make a backup of existed folder directory (and all contents in it) with new increase number in folder name.
#echo off
setlocal EnableDelayedExpansion
set "IncrNum=1"
:Start
::The following will set the "%PathFolder%" variable with path to folder name (%userprofile%\Desktop\TEST) and then will search if exist. If NOT exists, will create it (xcopy), else, If exist, will directing the "%PathFolder%" variable to :Search label (for-)loop section for further handling...
::Tip: Can be used %1 instead of %userprofile%\Desktop\TEST in [set "PathFolder=..."] line so it will work when you Drag-n-Drop a folder on this current saved batch file.
set "PathFolder=%userprofile%\Desktop\TEST"
if NOT exist "%PathFolder%" (
xcopy %PathFolder% %PathFolder% /i /y
exit /b
) else (
goto :Search
)
exit /b
:Search
::The following will search in the "%PathFolder%" variable (%userprofile%\Desktop\TEST) and will make a COPY of "TEST" folder (and all contents in it) with an increase number added in parenthesis at the end of folder name [like TEST(1)]. If alredy exist TEST(1) then will copy TEST folder as TEST(2) ... or TEST(3) ... and so on.
for /f "tokens=*" %%G in ('dir /b /s /a:d "%PathFolder%*"') do (
if exist %%G^(%IncrNum%^) (
echo At "%%~dpG" a folder "%%~nG(%IncrNum%)" alredy existed.
set /a IncrNum+=1
goto :Search
) else (
echo.
echo.
echo The "%%~nG" folder and all contents in it
echo will be copied now as "%%G(%IncrNum%)".
echo.
pause
xcopy %%G %%G^(%IncrNum%^) /i /y
exit /b
)
)
:EndBatch
set "PathFolder="
pause
exit

How can I move the contents of one directory tree into another?

I have a directory which contains files and a number of levels of subdirectories:
C:\Source
I would like to move the contents of C:\Source into:
C:\Destination
Requirements:
All files and all subdirectories
within C:\SourceData must be moved
I will be running the command in a
batch file
I can't use Powershell or
any other scripting languages
Attempt 0
XCOPY /E "C:\Source" "C:\Destination"
This works perfectly, but it copies instead of moves. I can't copy then delete the source as I'm moving a very large set of files and there isn't enough disk space to have two copies of them at a time.
Attempt 1
MOVE "C:\Source" "C:\Destination"
This moves the entire C:\Source directory into C:\Destination so I end up with:
C:\Destination\Source
Attempt 2
With some help from this question and accepted answer I came up with:
for /r "C:\Source" %%x in (*) do move "%%x" "C:\Destination"
This moves the files within C:\Source but not the subdirectories or their contents. Note that I used %%x instead of %x as I'm using it in a batch file.
Using FOR seems promising but I'm not sure I've used the right syntax? Have I missed something?
Attempt 3
As suggested by Nick D, I tried rename:
RENAME "C:\Source" Destination
For the example scenario I gave this works fine. Unfortunately my real Destination directory is at a different level to the Source directory and this doesn't seem to be supported:
C:\>REN /?
Renames a file or files.
RENAME [drive:][path]filename1 filename2.
REN [drive:][path]filename1 filename2.
Note that you cannot specify a new drive or path for your destination file.
I get "The syntax of the command is incorrect." errors if I try to specify a more complex destination path, for example:
RENAME "C:\Source" "C:\MyOtherDirectory\Destination"
RENAME "C:\Source" "MyOtherDirectory\Destination"
Undoubtedly use robocopy. It is a simple but brilliantly useful tool.
robocopy /move /e sourcedir destdir
This will move all the files and folders, including empty ones, deleting each original file after it has moved it.
If you don't have robocopy installed you can download it by itself or as part of a Microsoft resource kit.
Update:
Adjusted code to a. check whether folders already exist at the destination, in which case move files in that folder over (and continue traversing the source directory structure), otherwise move the folder wholesale.
At the end of the script the source folder is removed altogether to eliminate these folders which have had their files moved over to an already existent folder at the destination (meaning these folders have been emptied but not deleted at the source).
Additionally we check whether a folder is both empty and already exists at the destination in which case we do nothing (and leave the source folder to be deleted to the last line of the script). Not doing this results in "The filename, directory name, or volume label syntax is incorrect." errors.
Phew! Please let me know how you get on with this! I have tested this and it seems to be working well.
for /d /r "c:\source" %%i in (*) do if exist "c:\destination\%%~ni" (dir "%%i" | find "0 File(s)" > NUL & if errorlevel 1 move /y "%%i\*.*" "c:\destination\%%~ni") else (move /y "%%i" "c:\destination")
move /y c:\source\*.* c:\destination
rd /s /q c:\source
In response to ufukgun's answer:
xcopy C:\Source\* C:\Destination\* /s /e /i /Y
/s - Copies directories and subdirectories except empty ones.
/e - Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.
/i - If destination does not exist and copying more than one file, assumes that destination must be a directory.
/y - Suppresses prompting to confirm you want to overwrite an existing destination file.
As stated in another answer, using xcopy may be not as efficient as it would be a native move command that only changes pointers in the filesystem.
Since XCOPY works, you could use XCOPY and DELETE, it's a workaround, but should work?
on Vista use
robocopy source destination /MIR
/MIR .. mirror a complete directory tree (also deletes files in the destination)
else
xcopy
Of course you have to delete the source afterwards :)
I have a directory which contains
files and a number of levels of
subdirectories:
C:\Source
I would like to move the contents of
C:\Source into:
C:\Destination
Maybe I'm missing something, but can't you just rename the folder?
As sent on twitter:
Try combining attempt 3 with attempt 1. Rename to get the destination folder correct, then move "Destination" to the correct place.
#echo on
set SOURCE=C:\Source
set DESTINATION=C:\Destination
xcopy %SOURCE%\* %DESTINATION%\* /s /e /i /Y
PAUSE
i use batch file like this...
or simply call:
xcopy C:\Source\* C:\Destination\* /s /e /i /Y
I use a utility called xxcopy. It can move files and have many useful options, you can use it like this :
xxcopy C:\Source C:\Destination /E /RC
the options :
/E to copy everything even empty folders
/RC to remove every source file after each successful copy
you can download free copy of xxcopy for personal use from :
http://www.xxcopy.com/xcpydnld.htm
Maybe a little off-topic, but still usefull:
Some people suggest to just copy + delete the source files, but
moving files is not the same as copying + deleting!
When using the (x)copy function, you allocate new space on the same volume on a harddisk. After the copying the files, the old files (the old allocated space which was required for the files) are beign marked as deleted. While you will achieve the same result as an end-user, moving does something diffrent and more efficient.
Moving files actually only changes some records in the MFT (master file table). These changes only consist of a different path for the user to locate its files. Physically the files still remain in the same sectors on the harddisk.
If all your trying to do is move a directory and the content up one level:
MOVE folder_you_wan_to_move ..
Note that .. refers to the next directory up.
I leave this code I have written based on ljs's attempt,
It moves directory trees as Windows does, overwriting the files that already exists in destination with those in source, and avoiding the slow copy and erase method except if the destination is in a different drive.
If your S.O is not in english must change line 6 with the text used by the Dir command when it finds 0 files.
movedir.bat source_dir destination_dir
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
if %1.==. echo movedir dir1[\*] dir2 & echo move dir1 inside dir2 overwriting coincident files & echo option \* moves only dir1 content & goto end
set S=%~f1
set D=%~f2
set "noFiles= 0 File"
set "R=0" rem R is option [\*] flag
if %S:~-2%.==\.. set "S=%S:~,-2%" & set "R=1"
if not exist "%S%" goto paramERR
if not exist "%D%" goto paramERR
set "Trim=0" & set "Sc=%S%"
:LP
set /A Trim+=1 & (set "Sc=!Sc:~1!") & if NOT !Sc!.==. goto LP
if %R%==0 (if exist "%D%\%~n1%~x1" (set "D=%D%\%~n1%~x1")) else move /y "%S%" "%D%" & goto end
CALL:movefiles "%S%" "%D%"
for /D /R "%S%" %%I in (*) do (set "Way=%%~fI") & (set "Way=!Way:~%Trim%!") & if exist "%D%!Way!" (CALL:movefiles "%%I" "%D%!Way!") else (move /y "%%I" "%D%!Way!\.." > NUL)
rd /s/q "%S%" & if %R%==1 md "%S%"
goto end
:movefiles
dir %1 | find "%noFiles%" > NUL & if ERRORLEVEL 1 move /y "%~1\*.*" %2 > NUL
goto :eof
:paramERR
echo Source or Destination does not exist
:end
I think the easiest thing you could do is to modify your Attempt 2
from
MOVE "C:\Source" "C:\Destination"
to
MOVE "C:\Source\*" "C:\Destination"
KISS ;-)
Edit: this seem not to work, so my advice is to trash away the crappy DOS command line and use Cygwin with BASH as a shell! (or just add the cygwin binaries to the path so you can use mv within DOS, thus not having to change the shell as your requirements state).

Resources