Search code examples
linuxbashsortingimagemagicktiling

Bash enumarate files numerically with *


I wrote a script that visits each directory and uses imagemagick to montage them for tiling for gaming purposes.

find . -type d | while read d; do
        # $k = filename generated from folder name
        montage -border 0 -geometry +0+0 -background none -tile 6x $d/* ~/tiles/$k.png
done

It works nice when the images are named like these because order is preserved when using * : im_0001.png, im_0002.png... but it fails when somebody made the images names like these: im_1.png, im_2.png, .. because im_10.png comes before im_2.png and the order fails. It is not easy to fix the filenames by hand all the time, is there a way to enumarete the filenames via * but making it force to use the numerical order? I know the sort function has that capability but how can I do it in my script? As the filenames do not have a structure, I am curious how to accomplish this.


Solution

  • I believe you'll have to rename the files first:

    #!/bin/bash
    
    ext=.png
    
    for f in *$ext; do
      num=$(basename "${f##*_}" $ext)
      mv "$f" "${f%_*}_$(printf "%04d" $num)$ext"
    done