Batch script to rename PDF files using the content

前端 未结 1 775
旧时难觅i
旧时难觅i 2021-01-25 13:24

I have a batch script used to extract PDF information and rename the PDF then.

The script is working fine for 1 PDF file but I need to use it directly in a folde

相关标签:
1条回答
  • 2021-01-25 14:04

    Perhaps this commented batch file code works for moving all PDF files in current directory to subdirectory XYZ FOLDER with new file name determined from contents of each PDF file.

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    
    rem Don't know what this environment variable is for. It is not used by this code.
    set "DSUBDIX=%USERPROFILE%\Google Drive\CLASSEURS"
    
    md "XYZ FOLDER" 2>nul
    
    for /F "delims=" %%I in ('dir *.pdf /A-D /B 2^>nul') do call :RenamePDF "%%~fI"
    
    rem Restore initial command environment and exit batch file processing.
    endlocal
    goto :EOF
    
    
    :RenamePDF
    set "FilePDF=%~1"
    set "FileTXT=%~dpn1.txt"
    
    pdftotext.exe -raw "%FilePDF%"
    
    for /F "delims=- tokens=2" %%J in ('%SystemRoot%\System32\find.exe "Number=" "%FileTXT%"') do set "numeroa=%%J"
    for /F "delims== tokens=2" %%J in ('%SystemRoot%\System32\find.exe "NAME=" "%FileTXT%"') do set "nature=%%J"
    
    rem The text version of the PDF file is no longer needed.
    del "%FileTXT%"
    
    rem Move the PDF file to XYZ FOLDER and rename the file while moving it.
    move "%FilePDF%" "XYZ FOLDER\OCC-%numeroa:~0,5%#%nature%.pdf"
    
    rem The file movement could fail in case of a PDF file with new
    rem name exists already in target folder. In this case rename
    rem the PDF file in its current folder.
    if errorlevel 1 ren "%FilePDF%" "OCC-%numeroa:~0,5%#%nature%.pdf"
    
    rem Exit the subroutine RenamePDF and continue with FOR loop in main code.
    goto :EOF
    

    It is unclear for me why each *.pdf file should be moved into a subdirectory with new file name.
    This is not really necessary in my point of view. The command REN could be enough.

    For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    • call /?
    • del /?
    • dir /?
    • echo /?
    • endlocal /?
    • find /?
    • for /?
    • goto /?
    • md /?
    • move /?
    • rem /?
    • ren /?
    • set /?
    • setlocal /?

    Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line in a separate command process started in background.

    See also Where does GOTO :EOF return to?

    0 讨论(0)
提交回复
热议问题