0

I have a folder populated with PDF files in this format:

SI-T-xxxxxx.pdf
SI-T-xxxxxx-sol.pdf
SI-T-yyyyyy.pdf
SI-T-yyyyyy-sol.pdf
and so forth, with the middle part being digits.

I want a way for each pair of files to be merged in a single pdf, without the -sol

How can i do so in terminal? Thanks

2

The pdfunite utility seems to do what you're looking for (in Debian-like Linux distributions it is part of the poppler-utils package.

$ pdfunite a.pdf b.pdf c.pdf combined.pdf

Another option is GhostScript:

$ gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite =sOutputFile=combined.pdf a.pdf b.pdf c.pdf

ImageMagick also speaks GhostScript, so if you already are familiar with that:

$ convert a.pdf b.pdf c.pdf combined.pdf

Python also provides a PDF library, pdftools:

$ python3 pdftools/pdfmerge.py -o combined.pdf -d a.pdf b.pdf c.pdf

Regardless of which tool you use, we also need a way to pair off the files based on your described criteria. This brace-expanded glob should get the first of each pair:

SI-T-*{0..9}.pdf

So we can loop over that:

for pdf in SI-T-*{0..9}.pdf; do
    stuff
done

We can procedurally determine what the second file name would be based on the first:

$ pdf1='SI-T-xxxxxx.pdf'
$ pdf2="$(basename "$pdf1" .pdf)-sol.pdf"
$ printf "%s %s" "$pdf1" "$pdf2"
$ SI-T-xxxxxx.pdf SI-T-xxxxxx-sol.pdf

So let's work that into our loop:

for pdf1 in SI-T-*{0..9}.pdf; do
    pdf2="$(basename "$pdf1" .pdf)-sol.pdf"
    pdf3="$(basename "$pdf1" .pdf)-combined.pdf"
    if ! [[ -r "$pdf2" ]]; then
        printf "%s not found to merge with %s; skipping" "$pdf2" "$pdf1" >&2        
    else
        convert "$pdf1" "$pdf2" "$pdf3"
    fi
done
  • @steeldriver That's exactly what i needed, thanks a lot. Can you explain the syntax a bit? Kind of a Linux noob here ^^ – Merig Jan 11 at 16:40

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.