user3293909
user3293909

Reputation: 13

Batch File Move with Partial File Name to Partial Folder Name String

I have a directory full of folders that are named in this manner:

ABC-L2-0001__2ABC12345-0101_xxxx

I need to move a lot of files that are named in this manner to the folder that matches the first 9 characters of the files:

2ABC12345-0101.xyxyxyx.yxyxyxyxy.model

Here's what I'm trying based on reading some older posts of similar requests and it isn't working for me.

:start
@echo off
setlocal enableDelayedExpansion
for /f "tokens=*" %%f in ('dir *.model /b') do (
  set filename=%%f
  set folder8=!filename:~13,9!
  set "targetfolder="
  for /f %%l in ('dir "!folder8!"*.* /a:d /b') do (
     set targetfolder=%%l
  )
if defined targetfolder move "!filename!" "!targetfolder!"   
)   
:end

Any help would be greatly appreciated.

Upvotes: 1

Views: 1341

Answers (1)

Aacini
Aacini

Reputation: 67206

You exchanged the positions of fileName and folderName. You don't take the first 8 characters from file name, but characters 13,9, and you don't look for these characters at middle of the folder name, but at the beginning. Check this fixed code:

:start
@echo off
setlocal enableDelayedExpansion
for /f "tokens=*" %%f in ('dir *.model /b') do (
  set filename=%%f
  set folder8=!filename:~0,9!
  set "targetfolder="
  for /f %%l in ('dir "?????????????!folder8!*" /a:d /b') do (
     set targetfolder=%%l
  )
if defined targetfolder move "!filename!" "!targetfolder!"   
)   
:end

You also should know that for and for /D plain commands are more efficient than for /F combined with dir /B command.

:start
@echo off
setlocal enableDelayedExpansion
for %%f in (*.model) do (
   set filename=%%f
   set folder9=!filename:~0,9!
   set "targetfolder="
   for /D %%l in ("?????????????!folder9!*") do (
      set targetfolder=%%l
   )
   if defined targetfolder move "!filename!" "!targetfolder!"   
)   
:end

Upvotes: 2

Related Questions