DHuber
DHuber

Reputation: 17

batch copy/move files to folders with same name

I have a bunch of .xlsx files that are generated every month. I would like to be able to batch move the files to folders which have basically the same name.

Example: 123456 Action.xlsx, 123456 RC.xlsx, 123456 PF.xlsx would be the files. The folder would be 123456 Random Center.

Is there a way to move those files to that folder using a batch command or something else through the command prompt?

Here is the the code I have been trying to use/modify.

@echo off
pushd "C:\New folder"
rem Process all files in this folder separating the names at " "
for /F "tokens=1* delims=-" %%a in ('dir /B .xlsx') do (
   rem At this point %%a have the name before the " " and %%b the rest after " "
   rem Create the folder, if not exists
   if not exist "%%a" md "%%a"
   rem Move the file there
   move "%%a-%%b" "%%a"
)
popd

That creates a folder named %%a but puts nothing in it. I'm stuck and need some help.

Upvotes: 1

Views: 7434

Answers (1)

Dennis van Gils
Dennis van Gils

Reputation: 3452

First of all, welcome to Stack Overflow

In the code you provided you try to loop through files using the output of dir, and immediately split that up using spaces. Instead of this, you should use a for loop to loop through all files ending with *.xlsx first, and then brake that up in before and after the space.

Try this:

@echo off
pushd "C:\New folder"
FOR %%G IN (*.xlsx) DO (
  FOR /F "tokens=1 delims= " %%a IN ("%%G") do (
    if not exist "%%a Random Center" md "%%a Random Center"
    move "%%G" "%%a Random Center"
  )
)
popd
pause

In this code I first loop through all files ending with xlsx, by looping through xlsx ( is a wildcard) without a / switch. After that I loop through %%G (wchich are the filenames) as string using the /F switch.

Note that you're trying to use the - as a delimiter, instead of . You make the same error in your move command. If the files use a - instead of a , you should change the delimiter in my code as well.

EDIT:

This looks if there is a folder which starts with the same word as the files and moves them there:

@echo off
setlocal EnableDelayedExpansion
pushd "C:\New folder"
FOR %%G IN (*.xlsx) DO (
  FOR /F "tokens=1 delims= " %%a IN ("%%G") do (
    set "outFolder=%%a Random Center"
    for /D %%i in (*.*) do (
      for /F "tokens=1 delims= " %%b IN ("%%i") do (
        if "%%a"=="%%b" set "outFolder=%%i"
      )
    )
    if not exist "!outfolder!" md "!outfolder!"
    move "%%G" "!outfolder!"
  )
)
popd
pause

Upvotes: 3

Related Questions