Seanzies93
Seanzies93

Reputation: 341

How can I sort through a folder and move only specific files?

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?

Upvotes: 0

Views: 27

Answers (1)

Melebius
Melebius

Reputation: 6695

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%"
  )
)

Upvotes: 1

Related Questions