Search code examples
batch-filepdfmergepdftk

Batch: merge pdfs with same "filename-part" and pdftk


I want to merge some PDFs with pdftk. To merge pdfs with pdftk you have to use

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

But I have to merge a lot of pdfs with filenames like this

   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

The batch-script should parse the filenames and merge all files which starts with the same filename, like BCCM995_* oder QREM657_*.

"_" is the delimiter.

I have a bash-script with this funciton, but i need a batch-script.

#!/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

Can someone help me or recommend me a website to learn batch?

Thanks


Solution

  • Although I used to not answer questions that have not provided at least a small section of Batch file code, I do an exception in this case...

    @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
    

    For further details on any command, type help followed by the command name, or type the command with /? parameter; for example: for /?. In particular, you should look for "Delayed Expansion" questions on this forum...