0

I want to generate a list of file names containing n=1 to k, add the string "cat output xyz.pdf" at its end and pass the result as parameter to pdftk. It should execute as this:

pdftk file1.pdf file2.pdf file3.pdf cat output xyz.pdf

How can I automate this directly in the CLI?

3
  • Is k a fixed integer - or a shell variable? – steeldriver Feb 9 '20 at 18:04
  • A fixed integer. @steeldriver – gnidoc Feb 9 '20 at 18:24
  • By now you already know the answer but as a bonus you don't even need pdftk to merge files. pdfunite is part of poppler and installed by default in most distros. pdfunite file{1..k}.pdf xyz.pdf – Munzir Taha Feb 9 '20 at 18:59
1

If you are using bash as indicated by your question tag, there's no need for a loop: you should be able to use brace expansion.

Ex. for k = 32

pdftk file{1..32}.pdf cat output xyz.pdf

If the number of files is very large, this approach may become limited by ARG_MAX (resulting in an "argument list too long" error).

1
  • Perfect, thank you! – gnidoc Feb 9 '20 at 18:34
0

Something like this might be what you're after:

#!/bin/bash

filelist=""

for i in {1..5}; do
    filelist+="file${i}.pdf "
done

pkftk ${filelist} cat output xyz.pdf

The loop runs from 1..k and builds a string containing "file1.pdf ... filek.pdf". After the loop finishes, it runs pdftk passing the file list as well as the "cat output xyz.pdf" that you specified in your question.

If you want a one-liner, you can condense the above to (here assuming k=5):

pdftk $(for i in {1..5}; do printf "%s " file$i.pdf; done) cat output.xyz.pdf

The logic is the same, but I use command substitution to run the for loop; the $(...) is replaced with the output of ... (in this case, the file list). I use printf instead of echo as a way to avoid newlines.

2
  • I'd like to do it in one line, without saving a script first, if possible? – gnidoc Feb 9 '20 at 18:25
  • But it works. Thank you! – gnidoc Feb 9 '20 at 18:30

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.