Reputation: 143
I am trying to write a batch file that will search through a directory for *.pdf file extensions then convert them to *.tif file extensions with ImageMagic. I am able to do this if there is one PDF file in the directory, but if there are more than one I can't figure out how to convert them with the correct name. The problem is that within the loop, the fName
variable doesn't appear to be assigned, but outside the loop, it has a value...
Here is the code that works for a single PDF file and works for multiple, but the name containts ".pdf":
echo off
set dSource=C:\Users\Nick\Documents\Research\Journal Article\Figures
set fType=*.pdf
for /f "delims=" %%f in ('dir /a-d /b "%dSource%\%fType%"') do (
rem remove extension from file name, set value to variable:
set fName=%%~nf
rem call ImageMagic to convert to TIFF
rem convert -compose copy -density 300 -alpha off "%%f" "%%f.tif"
rem above line (when uncommented) lets multiple TIFF images to be produced, but they are *.pdf.tif
rem convert -compose copy -density 300 -alpha off "%fName%.pdf" "%fName%.tif"
rem above line (when uncommented) does not work because fName has no value...
rem variable value does not appear to be assigned within loop:
echo.file name within loop: %fName%
)
echo.file name after loop: %fName%
rem outside loop, variable value is now available...
rem convert -compose copy -density 300 -alpha off "%fName%.pdf" "%fName%.tif"
rem above line of code works, but only for the last file name with *.pdf discovered in directory
pause
Upvotes: 0
Views: 1452
Reputation: 41234
In your case a solution is to replace this:
convert -compose copy -density 300 -alpha off "%%f" "%%f.tif"
with this:
convert -compose copy -density 300 -alpha off "%%f" "%%~dpnf.tif"
rem or "%%~nf.tif" to save them all in the current folder.
The drawback with delayed expansion is that a !
character becomes more difficult to process in a filename or path or string.
Upvotes: 0
Reputation: 6657
Enable delayed expansion if you need to set a variable and use it in the same loop, and then refer to the variable in the loop using !
instead of %
:
@echo off
setlocal ENABLEDELAYEDEXPANSION
set dSource=C:\Users\Nick\Documents\Research\Journal Article\Figures
set fType=*.pdf
for /f "delims=" %%f in ('dir /a-d /b "%dSource%\%fType%"') do (
set fName=%%~nf
echo fName in the loop: !fName!
)
echo fName out of the loop: %fName%
Google "batch delayed expansion" for details.
Upvotes: 4