批处理:合并具有相同“文件名部分”和 pdftk 的 pdfs

问题描述 投票:0回答:2

我想用 pdftk 合并一些 PDF。 要将 pdf 与 pdftk 合并,您必须使用

"pdftk file1.pdf file2.pdf output file_final.pdf"

但是我必须合并很多文件名像这样的 pdfs

   BCCM995_KM_1.pdf
   BCCM995_KM_2.pdf
   BCCM995_KM_3.pdf
   QREM657_KM_1.pdf
   QREM657_KM_2.pdf
   QREM657_KM_3.pdf  
   QREM657_KM_4.pdf

批处理脚本应该解析文件名并合并所有以相同文件名开头的文件,例如 BCCM995_* 或 QREM657_*.

“_”是分隔符。

我有一个带有此功能的 bash 脚本,但我需要一个批处理脚本。

#!/bin/bash

for file in *_KM_1
  do
    number=$( echo $file | cut -d'_' -f1 )
    files=$(ls | grep "$number")
    echo "Found Number: $number"
    pdftk $files output output/$number.pdf
    echo "Wrote merged file to: /output/$number.pdf"
done

有人可以帮我或推荐一个网站来学习批处理吗?

谢谢

batch-file pdf merge pdftk
2个回答
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 *_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

有关任何命令的更多详细信息,请键入

help
后跟命令名称,或键入带有
/?
参数的命令;例如:
for /?
。特别是,你应该在这个论坛上寻找“延迟扩展”问题......


0
投票

你的脚本很好用,谢谢。 你能告诉我如何在脚本中再添加一件事吗?

目录中我的文件如下所示:

  • 111111_AAB.pdf
  • 111111_BBC.pdf
  • 222222_AAB.pdf
  • 222222_BBC.pdf

“AAB”和“BBC”是标识符。

这些文件将与您的脚本合并,只需对代码进行少量更改。 在下面的代码中,如何判断两个标识符是否存在然后合并?

"('dir /B *_*.pdf')"

但是,只有当两个文件都实际存在并且不只有一个文件存在时,才应合并文件。

合并后,是否可以只将合并后的文件“111111.pdf和222222.pdf”向上移动一个目录,删除已经合并的“AAB”和“BBC”文件?

由于我是批量初学者,我将不胜感激。

© www.soinside.com 2019 - 2024. All rights reserved.