0

I want to create a batch script to move my files to their respective folder according to their ID.

example:

file name E:\folderPath\Pre001Post.csv, will move to folder E:\folderPath\M001\

001 is the ID, the 'Pre' and 'Post' was random, 2 zero was leading for number less that 10.

file name E:\folderPath\Pre099Post.csv, will move to folder E:\folderPath\M099\

099 is the ID, the 'Pre' and 'Post' was random, 1 zero was leading for number less that 100.

file name E:\folderPath\Pre109Post.csv, will move to folder E:\folderPath\M109\

109 is the ID, the 'Pre' and 'Post' was random.

below was my script,

    @setlocal enabledelayedexpansion
    for /l %%S in (1, 1, 111) do (
         IF %%S LSS 10 ( SET z=00%%S ) ELSE (goto:moveFileProcess)
         IF %%S LSS 100 ( SET z=0%%S ) ELSE (goto:moveFileProcess)
    :moveFileProcess
         echo !z!
         echo %z%
    MOVE /Y E:\folderPath\???%z%????.csv E:\folderPath\M%z%\
    )

The problem was I not able set the variable %%s value to variable z (with the 00 leading).

I was follow Windows Batch files: what is variable expansion, and what does EnableDelayedExpansion mean? to add the @setlocal enabledelayedexpansion, but its still fail. Anyone know which part I was wrong?

YHTAN
  • 626
  • 5
  • 19
  • 1
    Well, you are already using delayed expansion when echoing `echo !z!`, so why not using it in the `move` command line also?? – aschipfl Jun 04 '19 at 11:50

1 Answers1

3

sorry, no labels and no goto allowed in a loop (except to jump out of the loop on a certain condition).

I rewrote your script a bit. You forgot to delay-expand z in the move command, and I implemented another way for your counter:

@setlocal enabledelayedexpansion
for /l %%S in (1001, 1, 1111) do (
   set "z=%%S"
   set "z=!z:~-3!"
   ECHO MOVE /Y "E:\folderPath\???!z!????.csv" "E:\folderPath\M!z!\"
)

Remove the ECHO command after troubleshooting / verifying it does what you want.

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • You could also use `set "z=!z:~1!"` to pointlessly save a character! You could also not add the intermediate `set` command and do the expansion directly, `MOVE /Y "E:\folderPath\???!z:~1!????.csv" "E:\folderPath\M!z:~1!"`. – Compo Jun 04 '19 at 12:02
  • @YHTAN, additionally, `"E:\folderPath\???!z!??.csv"` should also work because of the greedy nature of using the `?` wildcard, _(this still assumes three characters before the three digit number)_. However, please note that the wildcard would also move `"E:\folderPath\Pre099.csv"`, so be careful that you do not have filenames which may be picked up accidentally. Also, for the answer above to work, you would need to already have subdirectories `001..100` existing, _(this does not create none existing ones as `RoboCopy` can)_. – Compo Jun 04 '19 at 13:35