1

I’m trying to create a batch script in Windows 7 that will look at the first 6 numbers of 100s of pdf, create a folder based on the 6 unique numbers and move the pdfs into their respected folders. (There are some .pdfs that have the same 6 unique numbers)

The below batch almost works for me. It creates the folders for each unique 6 number pds however will not move all the documents: For Example: The following moves to 100036 folder 100036.pdf will move, 1000361.pdf will move. 1000361copy will move.

When there is a space in the file name, it will not move to the 100036 folder. 100036 - 1.pdf, 100036 - copy.pdf will not move

Any Ideas how to fix this?

Thank you in advance:

@echo off
REM This script creates folders based on file names and moves those files into the folders.  
REM *.pdf is the search term. Change this to search for different files.   
REM md %name:~0,6% will make a directory based on the first 6 characters of the file name. Change to 5% for the first 5 characters. 
REM move %* %name:~0,6% will move the file to the directory based on the first 6 characters of the file name. Change to 5% for the first 5 characters.

for /f %%F in ('dir/b/a-d *.pdf') do call :sub1 %%F
goto :eof

:sub1
set name=%1
md %name:~0,6%
move %* %name:~0,6%

Edited:

 @echo off
    for /f "tokens=*" %%F in ('dir/b/a-d *.pdf') do call :sub1 %%F
    goto :eof

    :sub1
    set name=%1
    md %name:~0,6%
    move %* %name:~0,6%
2

Because for /f split using space character, in order to process full file name, you should add "tokens=*" option :

for /f "tokens=*" %%F in ('dir/b/a-d *.pdf') do call :sub1 %%F

UPDATE: It is also needed to quote mv due to space character :

move "%*" "%name:~0,6%"
  • Thank you for your reply. I’m a newbie when I come to these batch scripts and I appreciate the assistance. I tried adding the line of code you have provided(see the edited code above) however it still doesn’t move files with a space in the file name. Any recommendations? – David Jul 29 '14 at 18:41
  • Strange, it works when I test it. In order to understand the problem, you should add some echo ==%*== in the :sub1 method. – mpromonet Jul 29 '14 at 18:55
  • Thank you for the reply. I found a solution. I found some code that removes the spaces for all the files and replaces the spaces with a _. Then what I have above works and everything moves to were it should. – David Jul 30 '14 at 12:49

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.