1

I need a batch file to copy files from a single folder to multiple folders, based on filename. The files are of the form aBBccccc.txt where a and ccccc do not matter, but BB are 2 character codes. For example files aQWertyu.txt aWErtyui.txt should be copied to folders QW and WE respectively, and these folders will be created by the script.

I've seen example scripts using the FOR /f, but cannot see how to parse the file, examine characters 2 and 3, then create the folder, and copy the files.

Thanks.

user1528218
  • 11
  • 1
  • 2

1 Answers1

5

This needs multiple parts:

  1. Delayed expansion. This is needed to get a substring from within the loop below:

    setlocal enableextensions enabledelayedexpansion
    
  2. A for loop for iterating over the files

    for %%x in (*.txt) do (
    
  3. Find the relevant substring:

        set "filename=%%x"
        set "folder=!filename:~1,2!"
    

    Note the use of !filename! here. This is using delayed expansion. Normally environment variables are referenced with %filename% but those would be expanded when parsing the complete loop which would then reduce %filename% to nothing. Delayed expansion, using ! solves this.

  4. Create the folder:

        if not exist !folder! mkdir !folder!
    

    This only creates the folder if it doesn't yet exist.

  5. Copy the file:

        copy "%%x" !folder!
    )
    

Putting it all together:

@echo off
setlocal enableextensions enabledelayedexpansion
for %%x in (*.txt) do (
  set "filename=%%x"
  set "folder=!filename:~1,2!"
  if not exist !folder! mkdir !folder!
  copy "%%x" !folder!
)
Joey
  • 344,408
  • 85
  • 689
  • 683
  • Thanks very much - perfect! For 'set "folder=!filename:~1,2!"' What's the rules for 1 and 2 - 1 is constant, then the next 2 characters? – user1528218 Jul 16 '12 at 08:16
  • 1 is the character to start the substring from, 2 is the length. – Joey Jul 16 '12 at 08:24
  • Thought so, but would that not make it 2,2, as the characters I want to use start at position 2 for 2 characters, or is the first character in position 0? – user1528218 Jul 16 '12 at 08:29
  • 1
    @user1528218 - The start position is zero based, 0 is the 1st char, 1 the 2nd, etc. – dbenham Jul 16 '12 at 10:58
  • One thing seems to be missing: after the second `if not exist ...`, there should probably something like this: `if not exist !folder! echo Well, I never...` :) Just joking, sorry. – Andriy M Oct 11 '12 at 11:49
  • The joys of having to piece together a contiguous script from the explanation ;) – Joey Oct 11 '12 at 12:52