Bash script qpdf to split multiple pdfs in 1 directory

721 Views Asked by At

I wrote a simple bash script as I need to split multiple pdfs into 2 pdfs on a regular basis. I need them to be split in the same sequence each time (pages 1-5 and 6 to last page). I need the newly split pdfs to be named uniquely so I can keep them apart (i.e. inv-1.pdf rec-1.pdf; inv-2.pdf rec-2.pdf, etc). My script only splits the 1 pdf when I have 5+ in the folder. Any suggestions are appreciated.

    #!/bin/bash
    for file in $(ls REQ*.pdf)

    do
        qpdf ${file} --pages . 1-5 -- inv-%d.pdf |\
        qpdf ${file} --pages . 6-z -- rec-%d.pdf |\
        echo >> ${file}
    done

'''

1

There are 1 best solutions below

4
On

Quick solution: Append | xargs echo to your ls command.

    #!/bin/bash
    for file in $(ls REQ*.pdf | xargs echo)

    do
        qpdf ${file} --pages . 1-5 -- inv-%d.pdf |\
        qpdf ${file} --pages . 6-z -- rec-%d.pdf |\
        echo >> ${file}
    done

Rationale: In your case, ls output is one filename per line. Your for loop picks up the filename in the same line only. The rest get ignored. You can read more about ls output behavior on this answer- What is the magic separator between filenames in ls output?

The pipe (|) redirects ls output to xargs which applies echo to generate space-separated file names on a single line. Read more about xargs on the man page