Batch file that searches for a folder with the same name as a local file and moves said file to the located folder not working

Viewed 200

So I am trying to create a batch file that will take a pdf file in the same directory as the batch file and output the file name (sans extension). I used this code to accomplish this:

@echo off

for /r "C:\Users\me\Test Folder" %%G in (*.pdf) do set "name=%%~nG"

This works fine. The next step is to search another directory and find a directory within the searched directory whose name matches the output of the above code (stored in the %name% variable). Here's what I tried:

dir "P:\Accounting\Acc Pay" | find %name% | set "loc=%%~dp"

The goal of the above code was to find only the directories that had the same name as the original pdf file and then set the drive and path of the output to a variable %loc%. I think this is where I messed up.

Once the path to the folder is set to %loc%, I then am supposed to finish with this line:

move .\*.pdf %loc%

This would take all the pdf files (there will only be one in the directory at once) in the directory with the batch file and move it to the path currently stored in the %loc% variable.

In total the code looks like this:

@echo off

for /r "C:\Users\me\Test Folder" %%G in (*.pdf) do set "name=%%~nG"

for /r %%A in ('dir "P:\Accounting\Acc Pay" | find %name%') do set "loc=%%~dpA"

move .\*.pdf %loc%

However, the code seems to move the pdf file into the same location it was already in (ie the folder with the batch file). I assume the %loc% variable is not working properly. Any help much appreciated.

1 Answers

Like @Magoo said (^|). And you surely want to add the following switches for the dir command: /b for "bare format" (name only) and /ad for "Attribute Directory" to return folder names only. find needs its's argument quoted, and for safety, the destination for the move command should also be quoted. Your find could benefit from /i to make it case-insensitive.

I personally would do it with nested loops to avoid creating superflouos variables:

@echo off
for /r "C:\Users\me\Test Folder" %%G in (*.pdf) do (
  for /r %%A in ('dir /b /ad "P:\Accounting\Acc Pay" ^| find /i "%%~nG"') do (
    move "%%G" "%%~dpA"
  )
)

Bonus: should there be more than one .pdf file (maybe after the Weekend or Holidays), this would process all of them correctly in one go.

Depending on your naming structures, consider replacing find /i "%%~nG" with findstr /iblc:"%%~nG" (see findstr /?to find out what the switches mean)

(Note to prevent confusion: findstr is the only command (as far as I'm aware) that supports concatenating switches into one. /iblc is the same as /i /b /l /c)

Related