I need to move files from a directory to another directory based on the files name. The files are in the format of 12345 123456.pdf
where the 2 string lengths can vary. There will always be a space between them though and they are always PDF files.
The destination directory is the SAME NAME as the first string of the filename (ex. 10003075 3000101012.pdf
destination directory would be 10003075
).
If the destination directory does not exist I DO NOT want it created. The file should be left in the initial directory.
The file structure is as such:
Main Folder
|
Destination Directories
Files waiting to be moved Directory
|
Batch file
So the Batch file would have to check the directory it is in for pdf files, then check the directory above it for the directory corresponding to the first string in the file name, then move that file to that directory only if it exists else leave the file where it is.
I have worked with some suggestions on stackoverflow but everything I have seen will either make the directory or move the file to the main directory if the directory is not there.
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir\t w o"
PUSHD "%sourcedir%"
FOR /f "tokens=1*delims= " %%a IN (
'dir /b /a-d "* *.pdf" '
) DO (
IF EXIST "..\%%a\." (ECHO(MOVE "%%a %%b" "..\%%a\") ELSE (ECHO(Leave "%%a %%b")
)
popd
GOTO :EOF
You would need to change the setting of sourcedir
to suit your circumstances. Assigning it to %~dp0
is a possibility.
Given (partial dir /a:d of %sourcedir%)
20/01/2015 09:49 <DIR> one
20/01/2015 09:49 <DIR> t w o
20/01/2015 09:50 <DIR> 1232
20/01/2015 09:50 <DIR> 1234
and dir of source of pdfs:
Directory of u:\sourcedir\t w o
20/01/2015 09:50 0 dum myfile2.pdf
20/01/2015 09:50 0 1231 54321.pdf
20/01/2015 09:50 0 1232 54321.pdf
20/01/2015 09:50 0 1233 54321.pdf
20/01/2015 09:50 0 1234 54321.pdf
20/01/2015 09:50 0 1235 54321.pdf
6 File(s) 0 bytes
This yields
Leave "dum myfile2.pdf"
Leave "1231 54321.pdf"
MOVE "1232 54321.pdf" "..\1232\"
Leave "1233 54321.pdf"
MOVE "1234 54321.pdf" "..\1234\"
Leave "1235 54321.pdf"
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
)
The Leave
message and its associated else
clause would of course be optional.
来源:https://stackoverflow.com/questions/28035754/batch-file-to-move-files-based-on-name-w-o-creating-new-folders