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

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

New contributor
Merig is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

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:


So we can loop over that:

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

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        
        convert "$pdf1" "$pdf2" "$pdf3"
  • @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

Merig is a new contributor. Be nice, and check out our Code of Conduct.

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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