1

I want to remove a known string .doc from the middle of a variable string %%f in a loop.
I have a batch file that converts a Word file to PDF:

echo Converting MS Word documents to PDF . . . cd /D "%mypath%\documents" for /f "delims=|" %%f in ('dir *.doc /S /B') do ( Q:\OfficeToPDF.exe "%%f" "%%f.pdf" ) 

Problem: The output files are named myfile.doc.pdf where I don't know the length of myfile in advance.

--> How can I remove .doc from that string?
Alternatively, replace .doc. with . would achieve the same goal. I think I need this kind of string substitution but I can't get it to work within that for loop. It would almost be like this, but it doesn't work:

for [...] do ( set outname=%%f:.doc.=.% && Q:\OfficeToPDF.exe "%%f" "%outname%" ) 

I've seen this and this (as well as many other questions) but I didn't see a solution that works in a loop. I found a Linux solution for it but that doesn't directly help me.

2 Answers 2

1

The for replaceable parameters can include a list of delimiters to extract only part of the content in the case of file/folder references (see for /?)

In your case %%~dpnf.pdf will return the drive, path, and name of the input file, with the string .pdf attached.

for /f "delims=" %%f in ('dir *.doc /S /B') do ( Q:\OfficeToPDF.exe "%%f" "%%~dpnf.pdf" ) 

Or still better

for /r %%f in (*.doc) do ( Q:\OfficeToPDF.exe "%%~ff" "%%~dpnf.pdf" ) 

where %%~ff is the reference to the file with full path

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant!! Thank you. Minutes after posting my question, I found a solution OfficeToPDF.exe "%%f" "%%~pf%%~nf.pdf" based on this answer but yours is even more concise.
1
...Q:\OfficeToPDF.exe "%%f" "%%~nf.pdf" 

should solve your problem.

~n selects the name part of the filename. See for /? from the prompt for documentation...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.