Reputation: 2450
I would like to create a Windows batch file that can accept the name of a file in as a parameter and then search for text within the PDF to rename the file. For example, I have a file called 123.pdf, inside that PDF there is the text "My Name: Paul". I would like to create a new copy of 123.pdf and call it Paul.pdf. I have created the file below but unfortunately it is not working, I think the issue is that it is trying to rename it to "My Name: Paul". The good news is that extracting the PDF text to a txt file is working fine thanks to pdftotext.exe
Please help.
@ECHO OFF
SETLOCAL
SET "sourcedir=C:\"
set pdffile=%1
pdftotext.exe %pdffile%.pdf
FOR /f "delims=" %%a IN ('findstr /B /L /c:"My Name:" "%sourcedir%\%pdffile%.txt"') DO (
echo %%a
SET myname=%%a
SET myname=myname: =%
SET myname=myname::=%
echo %myname%
echo COPY %pdffile%.pdf %myname%.pdf
COPY %pdffile%.pdf %myname%.pdf
)
Upvotes: 0
Views: 370
Reputation: 140168
Of course, you are right: you cannot rename a file using a name with :
in it in Windows because it's the drive/path separator.
For your script, you have to enabled delayed expansion for myname
, then use !
instead of %
in the loop (also fixed a problem when you're stripping spaces & colons from myname
but not the prefix!).
@ECHO OFF
setlocal ENABLEDELAYEDEXPANSION
SET "sourcedir=C:\"
set pdffile=%1
pdftotext.exe %pdffile%.pdf
FOR /f "delims=" %%a IN ('findstr /B /L /c:"My Name:" "%sourcedir%\%pdffile%.txt"') DO (
echo %%a
SET myname=%%a
rem ok but that doesn't remove My Name prefix
rem SET myname=!myname: =!
rem SET myname=!myname::=!
rem this does:
set myname=!myname:My Name:=!
echo COPY %pdffile%.pdf !myname!.pdf
COPY "%pdffile%.pdf" "!myname!.pdf"
)
Upvotes: 1