我正在尝试编写一个批处理文件,该文件将在目录中搜索* .pdf文件扩展名,然后使用ImageMagic将它们转换为* .tif文件扩展名。如果目录中有一个PDF文件,我可以这样做,但如果有多个PDF文件,我无法弄清楚如何使用正确的名称转换它们。问题是<循环中的, 以下代码适用于单个PDF文件,适用于多个,但名称包含“.pdf”:fName
变量似乎没有分配,但在循环外,它有一个值... < / p>
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
答案 0 :(得分:3)
如果您需要设置变量并在同一循环中使用它,请启用延迟扩展,然后使用!
而不是%
引用循环中的变量:
@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%
谷歌“批量延迟扩张”了解详情。
答案 1 :(得分:0)
在您的情况下,解决方案是替换它:
convert -compose copy -density 300 -alpha off "%%f" "%%f.tif"
用这个:
convert -compose copy -density 300 -alpha off "%%f" "%%~dpnf.tif"
rem or "%%~nf.tif" to save them all in the current folder.
延迟扩展的缺点是!
字符在文件名或路径或字符串中变得更难处理。