【问题标题】:Batch convert pdf files with pfdtk but with spaces in the name使用 pfdtk 批量转换 pdf 文件,但名称中带有空格
【发布时间】:2021-02-20 15:21:10
【问题描述】:

我正在尝试合并大量具有相似数字的 pdf 文件

例如“NR 01234567_1.pdf” “NR 01234567_2.pdf” ETC 在包含数千个类似文件页面的文件夹中,每个文件名需要合并 例如“NR 01234567.pdf”

我已经使用下面的脚本成功地处理了所有文件名中没有空格的文件(感谢这个论坛上一些非常有帮助的人),但它不适用于名称中的空格。

谁能帮我解决这个问题?

@echo off
setlocal EnableDelayedExpansion

rem Initialize (delete) "lastFile" and "fileList" variables
set "lastFile="
set "fileList="

rem Next line get the output of a "dir /B" command, that show file names *only*
rem "for /F" command execute the dir, get the output and divide each line in two "tokens" ("%%a" and "%%b")
rem with the first part before the "_" in "%%a" and the *rest* (including further "_") in "%%b"

for /F "tokens=1* delims=_" %%a in ('dir /B *.*') do (

   rem If the base file name changed...
   if "%%a" neq "!lastFile!" (

      rem Process previous file list;
      rem this "if" is just to avoid process the empty list the first time
      if defined fileList (
         pdftk !fileList! output !lastFile!.pdf
      )

      rem Reinitialize the new list
      set "lastFile=%%a"
      set "fileList=%%a_%%b"

   ) else (

      rem Append this file to current list
      set "fileList=!fileList! %%a_%%b"

   )

)

rem Process the last list
pdftk !fileList! output !lastFile!.pdf

【问题讨论】:

  • 作为最佳实践,在批处理文件中使用文件名或文件路径时应始终使用“引号”。出于同样的原因,您将它们与 IF 比较和 SET 命令一起使用。
  • Jeroen Grommen,我注意到您已经返回登录到此站点,但没有回复您官方提供的任何答案。请参阅当有人回答我的问题时我该怎么办?了解在这种情况下您可以选择哪些选项,因为没有接受答案的问题不会被本网站视为已回答。

标签: batch-file pdf merge pdftk


【解决方案1】:
  set "fileList="%%a_%%b""

) else (

  rem Append this file to current list
  set "fileList=!fileList! "%%a_%%b""

 pdftk !fileList! output "!lastFile!.pdf"

(两个地方)

[未尝试 - 我没有 pdftk (AFAIK)]

我们的想法是将filelist 构建为"xy abcd" "xy defg" - 故意包含引号 = 以便pdftk"xy abcd" "xy defg" 视为其文件组合列表和"xy doom" 作为目标文件(是的 - 我对这些名字有冒犯性。正如“新数学”所描述的那样,"it's the idea that counts")

【讨论】:

    【解决方案2】:

    我认为可能有更简单的方法来完成这项任务。我记得pdftk.exe 有一个cat 选项,它可以与通配符/glob 一起使用。因此,您可以使用该选项代替创建文件列表,而不是创建文件列表。

    这是一个例子,(请先在3 行更改pdftk.exe 的位置),然后以保存PDF 文件的目录作为当前目录运行它:

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    Set "tkPDF=P:\ath\To\pdftk.exe"
    Set "lastPreName="
    For /F "EOL=_ Tokens=*" %%G In ('Dir "*_*.pdf" /B /A:-D /O:N 2^> NUL
     ^| "%SystemRoot%\System32\findstr.exe" /I /R "^.[^_]*_[^_]*.pdf$"'
    ) Do For /F "Tokens=1,* Delims=_" %%H In ("%%~nG") Do (
        SetLocal EnableDelayedExpansion
        If /I Not "!lastPreName!" == "%%~H" (
            Echo="%tkPDF%" "%%~H_*%%~xG" cat output "%%~H%%~xG")
        EndLocal
        Set "lastPreName=%%~H")
    Pause
    

    如果您对当前仅显示将要运行的命令的输出感到满意,请从10 行中删除Echo=,并在13 行中删除可选的Pause

    【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2019-02-25
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2020-08-09
    • 2016-08-21
    • 1970-01-01
    • 2017-02-15
    相关资源
    最近更新 更多