0

我正在尝试编写一个批处理文件,该文件将在目录中搜索 *.pdf 文件扩展名,然后使用 ImageMagic 将它们转换为 *.tif 文件扩展名。如果目录中有一个 PDF 文件,我可以做到这一点,但如果有多个,我不知道如何用正确的名称转换它们。问题是在循环内fName变量似乎没有被赋值,但在循环外,它有一个值......

这是适用于单个 PDF 文件并适用于多个文件的代码,但名称包含“.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
4

2 回答 2

4

如果您需要设置一个变量并在同一个循环中使用它,则启用延迟扩展,然后使用!而不是引用循环中的变量%

@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%

谷歌“批量延迟扩展”了解详情。

于 2013-09-27T22:14:17.560 回答
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.

延迟扩展的缺点是!字符在文件名、路径或字符串中变得更难处理。

于 2013-09-28T08:06:17.643 回答