Search code examples
windowsbatch-filecmdimagemagickimagemagick-convert

Patternmatching with variable part, which is the same in different filenames


I have a lot of files in one directory named: world_map_1.png, world_map_2.png, world_country_1.png, world_country_2.png, ...

I want to use ImageMagick to append world_map_2.png to world_map_1.png and store the output in world_map.png. I want to do this for all files starting with world and ending with 1 and 2, so my approach was:

convert world_*_1.png world_*_2.png +append world_*.png

The problem is that * must be the same in all 3 names, so I need a kind of variable for this, which I could reuse in the 2nd and 3rd name.


Solution

  • I'd use a command to detect uniq "infixes":

    for image in world_*_*.png
    do 
        tmp="${image/world_/}"
        echo "${tmp/_*/}"
    done | sort -u
    

    Then, loop over them

    for token in $(for a in world_*_*.png; do tmp="${a/world_/}"; echo "${tmp/_*/}"; done | sort -u)
    do 
        convert "world_$token"_*.png +append "world_$token.png"
    done
    

    Creating some fake image files:

    touch world_{map,country,something,else}_{01..04}.png
    

    The command runs all of the following lines:

    convert world_country_01.png world_country_02.png world_country_03.png world_country_04.png +append world_country.png
    convert world_else_01.png world_else_02.png world_else_03.png world_else_04.png +append world_else.png
    convert world_map_01.png world_map_02.png world_map_03.png world_map_04.png +append world_map.png
    convert world_something_01.png world_something_02.png world_something_03.png world_something_04.png +append world_something.png