Getting filenames in the right alphanumerical order

Viewed 71

I'm having trouble with this command (suspect it's bash related, and not program specific)

montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 ./*.bluemap.jpg /media/

The problem is that it starts with the file 100002.bluemap.jpg, not the lowest number which is 2016.bluemap.jpg

All numbers don't exist, for example the next after 2016 is 6438, 6685,9879

Is there anyway to get it to do the job correctly, the right order?

Or do I need to create some list or something?

I'm little lost..

2 Answers

Sort the filenames using GNU sort and read the list into an array, then expand it in the montage invocation.

readarray -d '' -t files < <(printf '%s\0' ./*.bluemap.jpg | sort -z -t/ -k2n)
montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 "${files[@]}" /media/

See:

A variant of @oguz ismail's answer using xargs to stream the file-names arguments rather than a Bash array.

printf '%s\0' ./*.bluemap.jpg |
  sort -z -t/ -k2n |
    xargs -0 sh -c '
montage \
 -verbose \
 -label "%f" \
 -font "Helvetica" \
 -pointsize 10 \
 -background "#ffffff" \
 -fill "gray" \
 -auto-orient \
 -tile 8x6 \
 -geometry 200x200+2+2 \
 "$@" \
 /media/
' _

Split explanation of xargs -0 sh -c:

  • -0: The entries in the input stream are delimited by null.
  • sh -c 'script' _: The command executed by xargs is an inline shell script whith the arguments from the input stream.

Alternatively to an inline shell script:

{
  # Create the null-delimited list of input file names
  # matching the globbing pattern ./*.bluemap.jpg
  printf '%s\0' ./*.bluemap.jpg |
    # Sort the null delimited list of file names
    sort -z -t/ -k2n;
  # At this point, the null-delimited list contains the sorted input files
  # Append the `/media/` destination argument as last entry
  printf '/media/\0';
} | xargs -0 \
      montage \
        -verbose \
        -label "%f" \
        -font "Helvetica" \
        -pointsize 10 \
        -background "#ffffff" \
        -fill "gray" \
        -auto-orient \
        -tile 8x6 \
        -geometry 200x200+2+2
Related