Search code examples
bashpowershellbatch-fileimagemagickpdftk

ImageMagick - Merge files with partial filename matches


these are my filenames in the folder

1710190363_1.jpg
1710190363_2.jpg
1711140603_1.jpg
1711140603_2.jpg
1711140603_3.jpg
1711140603_4.jpg
1711140603_5.jpg

All are .jpg files. File names are dynamic but unique count, first 10 digits then underscore following by a single digit.

Using imagemagick, I m trying to convert all the image files into pdf based on their first ten digits. I want the output as follows

1710190363.pdf
1711140603.pdf

Manually I got this run -

convert 1710190363_1.JPG 1710190363_2.JPG 1710190363.pdf

but dont know how to run in a loop

for %a in (*.jpg) do convert %a o_%a.pdf

Could anyone help me on this script.


Solution

  • This is a very simple solution, which assumes that:

    • the numbers behind the _ always start counting at 1;
    • the processing order of the equally prefixed files does not matter;

    So here is the code to be used within a batch script:

    for /F "delims=_" %%F in ('dir /B /A:-D "*_1.jpg"') do convert "%%F_*.jpg" "%%F.pdf"
    

    And here is the code to be used directly in command prompt (cmd):

    for /F "delims=_" %F in ('dir /B /A:-D "*_1.jpg"') do @convert "%F_*.jpg" "%F.pdf"