How can i find the path, filename and foldername of an "for /R"?

87 views Asked by At

I've written a batch-file, which renames all the PDF-files in the current folder and all its subfolders.

There are problems...

  1. When I use For /R %%I I cannot find the path of the file, name and foldername.

  2. When I don't use the above, it only finds in the current folder but the script works.

  3. I only know the For %%i command to be able to use set foldername=%%i which is probably not how I'm supposed to do it. I now need multiple do set* in order to write each piece of information.

The result i want it from a pdf in path: C:\Users\Downloads\AREA 1\xyyz.pdf to automatically rename to C:\Users\Downloads\AREA 1\AREA 1_xyyz.pdf when the script is in the map C:\Users\Downloads
And preferably move the file over afterwards. Yet I cannot seem to be able to command the file itself when using For /R.

When using the For /R command I cannot seem to access the right filename, mapname and filepath in order to change it's name.

echo on
setlocal enabledelayedexpansion
set "folderpath=%~dp0"

cd %folderpath%
for /r %%I in ("*.pdf") do ( for %%i in (.) do ( (set fname=%%i) & for %%I in (.) do ( (set fldnm=%%~nxI) & call :rename ) ) )
@pause
goto :eof

:rename
echo "%fldnm%_%fname%"
ren "%fname%" "%fldnm%_%fname%"
@pause
goto :eof

endlocal
pause
2

There are 2 answers

6
Aacini On BEST ANSWER

I don't understand what your code does... However, this solution does what your description specify:

EDIT: Small rename problem fixed

echo on
setlocal enabledelayedexpansion
set "folderpath=%~dp0"

cd %folderpath%
for /F "delims=" %%I in ('dir /B /S *.pdf') do (
   set "fldnm=%%~pI"
   for %%i in ("!fldnm:~0,-1!") do (
      ren "%%~fI" "%%~ni_%%~nI%%~xI"
   )   
)

@pause
goto :eof
0
OJBakker On

@Aacini original answer with added 'double-rename'-protection. The same can be used on Aacini's updated answer without for/R.

The original name is saved in a variable, try to delete the rename prefix from the variable and try to delete the original name from the variable. If the variable is now empty it is no longer defined and the rename must be done.

echo on
setlocal enabledelayedexpansion
set "folderpath=%~dp0"

cd %folderpath%
for /R %%I in ("*.pdf") do (
   set "fldnm=%%~pI"
   for %%i in ("!fldnm:~0,-1!") do (
      set "RenDone=%%~nI"
      set "RenDone=!RenDone:%%~ni_=!"
      set "RenDone=!RenDone:%%~nI=!"
      if not defined RenDone ren "%%~fI" "%%~ni_%%~nI%%~xI"
   )   
)

@pause
goto :eof