0

I have a ton of .zip files in a folder that I want to move into a new folder I made IF it fulfills a certain condition in its name. Like, if it has the date inside the filename, I want to move it into the folder. cd C:\Users\eyousea\Documents\Test

    set today=%date:~10,13%%date:~4,2%%date:~7,2%
    md %today%

    for %%a in (*.zip) do(
    set fileday=%%a:~1,8%
    if %today% = %fileday% (
    move %%a "C:\Users\eyousea\Documents\Test\%today%"

    pause

I'm not sure what's wrong. How can I accomplish this?

Seanzies93
  • 321
  • 1
  • 6
  • 12
  • It seems you are hitting the delayed expansion trap. See [this page](http://ss64.com/nt/delayedexpansion.html) for more information. See this question for a relevant example http://stackoverflow.com/questions/29594200/how-to-batch-move-files-date-filename-folder – user4317867 Jul 16 '15 at 06:06

1 Answers1

1

Use echo on and echo AProblematicCommand (for example echo set fileday=%%a:~1,8%) to debug batch-files!

  1. The block closed in parentheses is parsed and %’s expanded at once. So the fileday value used in if contains its value before the for loop starts – probably undefined!

    You need to enable delayed expansion and use ! to mark where to use it.

  2. You have to put space between do and (.

  3. A parameter like %a (or %%a in for) cannot be used for variable expansion. You have to assign it to a temporary variable and expand that.

  4. You can use indentation in batch-files, just for readability. It helps to find unclosed parentheses, for example. I cannot see any ) in your snippet.

To summarize:

set today=%date:~10,13%%date:~4,2%%date:~7,2%
md %today%
setlocal EnableDelayedExpansion

for %%a in (*.zip) do (
  set filename=%%a
  set fileday=!filename:~1,8!
  if %today% == !fileday! (
    move %%a "C:\Users\eyousea\Documents\Test\%today%"
  )
)
Melebius
  • 6,183
  • 4
  • 39
  • 52
  • First off thanks for the explanation. However, it doesn't work. Just as a heads up, in the if statement it's a == instead of just a =, but I'm sure you would notice that. But more importantly, it says the syntax of the move statement is incorrect and won't move it. I think it's because the filename is just the file name and not the actual path. How would I amend that? – Seanzies93 Jul 16 '15 at 16:47
  • @Seanzies93 Thanks for `==`. The `move` syntax should be correct, unless there are spaces in the filename or something similar. Could you post an example of your `move` command after expansion and the error message? – Melebius Jul 17 '15 at 06:36