I have a folder containing a number of files with the following filename structure:

John Doe - title.pdf
John Doe - title2.pdf
John Doe - title3.pdf
Jane Smith - some title.pdf
Jane Smith - second title.pdf

I wish to combine the pdfs starting with the same two words as part of their filename to get the following:

John Doe.pdf
Jane Smith.pdf

How would I go about it in Linux using a script and any of the tools available under Linux?

  • Does it matter which one will be the first set of pages when opened between the two? It'll never be more than two that need to be merged as well, correct? Just wanted to ask for clarification at this level in case it matters for the solution you are looking for. – Pimp Juice IT Jul 24 '16 at 16:09
  • The order doesn't matter. There might be two or three matching files. – To Do Jul 24 '16 at 18:21
  • If you can look at the examples from these two pages, you should be able to come up with some example code to try - not sure anyone wants to write all the code for you. But using pdftk and bash script should be possible. maketecheasier.com/combine-multiple-pdf-files-with-pdftk and this one stackoverflow.com/questions/20669033/… – dbmitch Jul 24 '16 at 19:43
  • Also per the PDFtk example, I'm not sure how you'd loop that in bash but in batch I've used it for similar purposes without the file name string matching logic like so to give you another pointer to start writing some logic with it perhaps: %pdftk% %sourcedir%\*.pdf cat output %outputdir%\combined.pdf It works well for merging PDF files on Windows so I assume it works just as well with Linux, etc. Post some code with an update on your question once you give it a try and I'm sure someone here can help you once you show more work from your side with PDFtk. – Pimp Juice IT Jul 24 '16 at 20:58

A bit old I know, I wanted such a script:

  • list files having a hyphen character
find -iname '*-*.pdf'
  • keep the part before the hyphen
find -iname '*-*.pdf' | sed "s/-.*$//"
  • remove duplicates: you have the prefixes you want ("John Doe", "Jane Smith") (you could ignore prefixes having only one occurences but this is probably not be required if the combine pdf command is happy with one file and just copies it)
find -iname '*-*.pdf' | sed "s/-.*$//" | sort -u
  • loop over the prefixes, for each one get the list of the files starting with this prefix and combine them
IFS=$'\n';for prefix in $(find -iname '*-*.pdf' | sed "s/-.*$//" | sort -u) ; do pdfunite $prefix* $prefix.pdf ; done
|improve this answer|||||
  • Thanks also for the explanation. I couldn't figure out how to go about it myself. It worked like a charm. – To Do Jul 27 '16 at 17:23

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.