Reputation: 1
I am trying to create a .bat file to move the files with the specific string to a specific folder.
For Ex. C:\Test
in this Test Folder there are several files like:
test-101.txt
test-102.doc
Also I have created the folder D:\Destination and in that several folders such as:
test-101
test-102
I want to match the string 'test-101'
and move it to folder 'test-101'
. Same for 'test-102.doc'
it will move to test-102
. I have thousands of files like that and folders too, so I cannot write the name of the file or folder in script. Please tell me the solution to match and move the files automatically. I have tried several strings and it only moves the file with specified name in batch file.
Upvotes: 0
Views: 3796
Reputation: 130919
No batch script required.
If the destination folders already exist, then
for %F in (c:\test\*) do move "%F" "d:\destination\%~nF\" >nul
If the destination folders may not exist yet, then
for %F in (c:\test\*) do (md "d:\destination\%~nF"&move "%F" "d:\destination\%~nF\") >nul
If you do end up using this code within a batch script, then don't forget to double up all the percents.
Upvotes: 2
Reputation: 80213
@ECHO OFF
SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=c:\sourcedir"
SET "destdir=c:\destdir"
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*" '
) DO (
ECHO MD "%destdir%\%%~na"
ECHO MOVE "%sourcedir%\%%a" "%destdir%\%%~na\"
)
GOTO :EOF
The required MD commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO MD
to MD
to actually create the directories. Append 2>nul
to suppress error messages (eg. when the directory already exists)
The required MOVE commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE
to MOVE
to actually move the files. Append >nul
to suppress report messages (eg. 1 file moved
)
Note also that if the source and destination are on different drives, you may need to COPY /B
the files rather than MOVE
ing them. You'd no doubt also need to delete the file from its original location.
Upvotes: 0