Search code examples
batch-filebatch-rename

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


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

Solution

  • 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