Windows .BAT to move all directories matching mask from dir A to dir B - windows

I want to write a .BAT file to move all sub-directories (whose name matches a mask) of C:\WINNT\Temp to H:\SOMEOTHERPLACE.
So if my mask is ABC* then the directories :
C:\WINNT\Temp\ABC1
C:\WINNT\Temp\ABC2
C:\WINNT\Temp\ABC3
should be moved to
H:\SOMEOTHERPLACE
and everything else (including files, as opposed to directories, which match the mask) should not. I do want to move them and not copy.
Can anyone point me in the right direction ?

OK I've figured this out. If you write a movedirs.bat file containing the single line
for /d %%X in (%1) do move %%X %2\%%~nX
And then run it (with argument 1 being the mask for the directories I want to move and argument 2 being the directory I wish to move the directories to) as
C:\>movedirs.bat C:\WINNT\Temp\ABC* H:\SOMEOTHERPLACE\
It produces the effect I want.
The /d argument on the 'for' ensures that only directories are processed. The '~n' modifier on the %%X variable means that the original sub-directory name (as opposed to the entire path) is used as the target within the second command line argument.
Just for the sake of posterity in investigating this I did something similar with xcopy but then i would have had to get involved in deleting the source so for my purposes move works better but for the record here's the same idea wrapped around xcopy.
for /d %%X in (%1) do xcopy %%X %2\%%~nX /E /I
To process directories with as well as without extensions, for example "C:\MyDir*.MyExt" above command will need a combined (filename+extension) modifier "~nx":
for /d %%W in (%1) do xcopy %%W %2\%%~nxW /E /F /R /Y /I

[Comments are useless for structured answers so I'll repeat the comment here - with a couple of edits !]
Thanks for your answer but I've found that you can't use xcopy with a wildcard on the source. Or rather you can use wildcards but then you get only the directories being created without any content. So if you do this ...
H:\SOMEOTHERPLACE>xcopy C:\WINNT\Temp\ABC1 /E
... you'll get the the ABC1 directory copied to your current directory as you might reasonably expect but if you do this ...
H:\SOMEOTHERPLACE>xcopy C:\WINNT\Temp\ABC* /E
... you'll get each directory name present in C:\WINNT\Temp appearing in your current directory but those directories will be empty ! Please tell me I'm wrong but that's what I find !

Related

How do I get a relative path out of a windows batch file using echo?

How do I get relative directories / partial paths to display as echo output from a windows .bat file?
How to split the filename from a full path in batch?
Talks about everything but.
I've found drive letters, filenames, extensions, shortened (8.3) names, and full paths - but no relative paths.
I'm running a recursive FOR /R loop; which traverses sub-directories. I would like something - that doesn't have twenty characters of useless path info - that tells me which directory each duplicate file lives in... without hardcoding the .bat file to live in a certain directory/path?
Maybe a solution would be to measure the length of the script's path and cut that off of the front of the full path? But I don't know how to manipulate that.
Script could be in many locations:
F:\a.bat<BR>
F:\Dir1\fileA.txt<BR>
F:\Dir20\fileA.txt
C:\Users\Longusername\Desktop\Container\a.bat<BR>
C:\Users\Longusername\Desktop\Container\Dir1\fileA<BR>
C:\Users\Longusername\Desktop\Container\Dir20\fileA
And right now the only options I have for output are (%%~nxG):
fileA.txt
fileA.txt
Which doesn't tell me which directory each file is in...or (%%~pnxG)
\Users\Longusername\Desktop\Container\Dir1\fileA.txt
\Users\Longusername\Desktop\Container\Dir20\fileA.txt
What I'd like, from any location:
\Dir1\fileA.txt
\Dir20\fileA.txt
Could be missing the leading \, but that's negligible. Other options than echo are permissible if they'll work on most window machines. They may lead to more questions, though - as I've figured out my other pieces with echo.
quite easy, if you think about it: just remove the current directory path (%cd%):
#echo off
setlocal enabledelayedexpansion
for /r %%a in (*.txt) do (
set "x=%%a"
echo with \: !x:%cd%\=\!
echo without \: !x:%cd%\=!
)
By the way: \folder\file always refers to the root of the drive (x:\folder\file), so it's not exactly a relative path.
This is similar to the already accepted answer, but with delayed expansion enabled only where needed. This should correctly output filenames containing ! characters.
#Echo Off
SetLocal DisableDelayedExpansion
Set "TopLevel=C:\Users\LongUserName"
For /R "%TopLevel%" %%A In ("*.txt") Do (
Set "_=%%A"
SetLocal EnableDelayedExpansion
Echo=!_:*%TopLevel%=!
EndLocal
)
Pause
You could also use Set "TopLevel=%~dp0", (the running script's directory) or Set "TopLevel=%~dp0..", (the running script's parent directory)
One potential benefit of the above method is that you can also use a location relative to the current directory for the value of %TopLevel% too, (in this case, based upon the initial example, the current directory would be C:\Users):
Set "TopLevel=LongUserName"
Although this would only work correctly if LongUserName didn't already exist as content of the path earlier in the tree.
You could use xcopy together with its /S (include sub-directories) and /L (list but do not copy) options since it returns relative paths then, so you do not have to do any string manipulation, which might sometimes be a bit dangerous, particularly when the current directory is the root of a drive:
xcopy /L /S /I /Y /R ".\*.txt" "\" | find ".\"
The appended find command constitutes a filter that removes the summary line # File(s) from the output.
To capture the output of the aforementioned command line just use a for /F loop:
for /F "delims=" %%I in ('
xcopy /L /S /I /Y /R ".\*.txt" "\" ^| find ".\"
') do (
rem // Do something with each item:
echo/%%I
)

remove the directory from output in batchfile

I have the below batchfile that output ReadFile.txt file
cd /d "T:\EMP\SST"
for /r %%i in (T:\EMP\SST) do echo %%i >>D:\MultiThreading\ReadFile.txt
pause
this ReadFile.txt file output
T:\EMP\SST\T:\EMP\SST
T:\EMP\SST\file 11\T:\EMP\SST
T:\EMP\SST\file 12\T:\EMP\SST
T:\EMP\SST\file 13\T:\EMP\SST
I want to remove the directory ouptput T:\EMP\SST so I want my output to be like this
file 11
file 12
file 13
how to do this
I believe you actually need for /D rather than for /R for your task (because I assume file 11, file 12, file 13 are actually directories as they are enumerated by for /R):
for /D %%I in (T:\EMP\SST\*) do echo %%~nxI
Anyway, your for /R syntax is wrong; the directory you want to enumerate recursively needs to be stated immediately after the /R switch (if you omit it, the current directory is assumed), and you need to provide a set (that is the part in between parentheses) that constitutes a pure file name pattern only, without any (absolute or relative) paths, like *.*, for example, to match all files.
In your code, for /R enumerates the current directory. Since your set is T:\EMP\SST and contains no wildcards (*, ?), it is just appended to the enumerated directories literally, because for accesses the file system only in case wildcards are encountered. That explains your weird output.
you're using FOR in a wrong way. The pattern between the parentheses isn't the start directory, it is the file/directory pattern you want to match. Here I suppose you want *.*
If you only want the filenames (no paths at all) you can write:
#echo off
for /r T:\EMP\SST %%i in (*.*) do echo %%~nxi>>D:\MultiThreading\ReadFile.txt
If you want the filenames + relative paths, it's slightly more complicated but doable, by enabling delayed expansion to be able to remove the path prefix + backslash:
#echo off
setlocal enabledelayedexpansion
set start_path=T:\EMP\SST
for /r %start_path% %%i in (*.*) do (
set f=%%i
echo !f:%start_path%\=!>>D:\MultiThreading\ReadFile.txt
)
This FOR command is cryptic and I have to read the help (FOR /?) everytime, but the fact is: everything useful is in there so I do it all the time :)

Windows Batch File Looping Through Directories to Process Files?

I need to write/use a batch file that processes some imagery for me.
I have one folder full of nested folders, inside each of these nested folders is one more folder that contains a number of TIF images, the number of images vary in each folder. I also have a batch file, lets call it ProcessImages.bat for Windows that you can "drop" these TIF files on (or obviously specify them in a command line list when invoking the bat); upon which it creates a new folder with all my images process based on an EXE that I have.
The good thing is that because the bat file uses the path from the folders you "drop" onto it, I can select all the TIFs of one folder and drop it to do the processing... but as I continue to manually do this for the 300 or so folders of TIFs I have I find it bogs my system down so unbelievably and if I could only process these one at a time (without manually doing it) it would be wonderful.
All that said... could someone point me in the right direction (for a Windows bat file AMATEUR) in a way I can write a Windows bat script that I can call from inside a directory and have it traverse through ALL the directories contained inside that directory... and run my processing batch file on each set of images one at a time?
You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
#echo off
call :treeProcess
goto :eof
:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
for %%f in (*.tif) do echo %%f
for /D %%d in (*) do (
cd %%d
call :treeProcess
cd ..
)
exit /b
Aacini's solution works but you can do it in one line:
for /R %%f in (*.tif) do echo "%%f"
Jack's solution work best for me but I need to do it for network UNC path (cifs/smb share) so a slight modification is needed:
for /R "\\mysrv\imgshr\somedir" %%f in (*.tif) do echo "%%f"
The original tip for this method is here
Posting here as it seems to be the most popular question about this case.
Here is an old gem I have finally managed to find back on the internet: sweep.exe. It executes the provided command in current directory and all subdirectories, simple as that.
Let's assume you have some program that process all files in a directory (but the use cases are really much broader than this):
:: For example, a file C:\Commands\processimages.cmd which contains:
FOR %%f IN (*.png) DO whatever
So, you want to run this program in current directory and all subdirectories:
:: Put sweep.exe in your PATH, you'll love it!
C:\ImagesDir> sweep C:\Commands\processimages.cmd
:: And if processimages.cmd is in your PATH too, the command becomes:
C:\ImagesDir> sweep processimages
Pros: You don't have to alter your original program to make it process subdirectories. You have the choice to process the subdirectories only if you want so. And this command is so straightforward and pleasant to use.
Con: Might fail with some commands (containing spaces, quotes, I don't know). See this thread for example.
I know this is not recursion (iteration through enumerated subdirectories?), but it may work better for some applications:
for /F "delims=" %%i in ('dir /ad /on /b /s') do (
pushd %%i
dir | find /i "Directory of"
popd
)
Replace the 3rd line with whatever command you may need.
dir /ad - list only directories
The cool thing is pushd does not need quotes if spaces in path.
rem Replace "baseline" with your directory name
for /R "baseline" %%a in (*) do (
echo %%a
)

Batch File to Delete Files in Folders

I have many folders in a directory that contain various files. Each filename begins with XXX_ where XXX could be the name of the folder the file is in. What I am needing to do is to go through all those folders and delete any file where XXX is the name of the folder that file is in.
Please have an eye out this question: Iterating through folders and files in batch file?.
I think this should help you.
Please let me know if you need further assistance.
EDIT #1
The joker character in DOS command line is *. Then, while searching a directory for certain files, you may consider your regular expression, that is, your XXX_, and complete it with *, this shall return only the files for which you're looking for.
This means that instead of *.zip pattern in one of the FOR loops given the linked question, your first FOR loop should contain your directory name, then take this variable concatenated with the * character to obtain only the files you're looking for.
For example, consider trying the following:
dir /s XXX_*.*
This should return only the files you're interested in, given the right folder name.
EDIT #2
Thanks for having precised your concern.
Here is a code sample that, I do hope so, should help. Now I know you say you have the looping correct, so that perhaps only piece of this code might be needed.
#echo off
setlocal enableextensions enabledelayedexpansion
for /F "delims==" %%d in ('dir /ogne /ad /b /s .') do (
for /F "delims==" %%f in ('dir /b "%%d\%%~nd_*.*"') do (
echo %%d\%%f
)
)
endlocal
This works and lists the files contained in subfolders from the current (.) folder.
I have tested it from the following folder:
C:\Docume~1\marw1\MyDocu~1\MyMusi~1
Where a 'XXX' folder is contained. This 'XXX' folder contains the following files:
Copy of XXX_blah.bmp;
XXX_blah.bmp;
XXX_1234.ppt;
XXX_textfile.txt.
From this structure, the output is:
C:\Docume~1\marw1\MyDocu~1\MyMusi~1\XXX\XXX_blah.bmp
C:\Docume~1\marw1\MyDocu~1\MyMusi~1\XXX\XXX_1234.ppt
C:\Docume~1\marw1\MyDocu~1\MyMusi~1\XXX\XXX_textfile.txt
I then suspect that putting a del instruction instead of an echo command shall do the trick. This means that to isolate the foldername itself from its path, you need to use the ~n instruction with your folder variable name like %%~nd, where your iterating folder variable name is %%d.
Furthermore, you could even use a parameterized batch file in the process, instead of hardcoding it, that is, if your 'set YourFolder =...' is part of your production code. This could look like:
#echo off
setlocal...
set root = %1
set root = %root:~1%
set root = %root:~0,-1%
...
endlocal
Instead of having '.' as pictured in my first FOR loop, your would replace it with "%root%" in order to consider your command line parameter instead of a hardcoded filepath.
I do help this helps, sincerely!
As Ron says, since the question is tagged "windows".
EDIT:
Ron's answer, which seems to have disappeared!, was to use del /s
EDIT2:
OK, it's valid only for file names, not for directories. For the directories you'd have to use something like sketched below.
Additional info: when you want to do the same thing recursively to files in a directory tree, and (unlike del) there's no command that already does the traversing for you, you can use the /R option of the for command.
To see the for command's docs, do e.g. start "for-help" cmd /k for /?.
Cheers & hth.,
– Alf
cd C:\"foldername"
del /s XXX_"*"
cls
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