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.

Torben Gundtofte-Bruun
  • 2,104
  • 1
  • 24
  • 34

2 Answers2

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

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Brilliant!! Thank you. Minutes after posting my question, I found a solution `OfficeToPDF.exe "%%f" "%%~pf%%~nf.pdf"` based on [this answer](http://stackoverflow.com/a/343846/20571) but yours is even more concise. – Torben Gundtofte-Bruun Feb 24 '15 at 11:52
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...

Magoo
  • 77,302
  • 8
  • 62
  • 84