合并pdf与PDFTK和相同的起始文件名

时间:2017-11-29 23:01:42

标签: batch-file

我正在尝试使用pdftk在目录中搜索类似的文件名并将它们组合起来。

我找到了一个由Aacini编写的精彩剧本,当它与NAME_KM_1,NAME_KM_2,NAME_KM_3等格式一起使用时效果很好。它会将所有 KM 的文件合并为pdf。

在我的场景中,我的文件名都是从Q1111_CONFIRM,Q1111_ORDER,Q2222_CONFIRM,Q2222_ORDER开始的。我如何修改这个以组合订单/确认匹配Qnumber?我尝试了一些不同的事情但没有成功。

@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 f 
urther "_") in "%%b"

for /F "tokens=1* delims=_" %%a in ('dir /B *_KM_*.*') 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

1 个答案:

答案 0 :(得分:0)

@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