質問

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.

役に立ちましたか?

解決

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

他のヒント

You can add this program to your system, as (for example) /usr/local/bin/human_sort

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import re

def sortable_list(s):
    elements=re.split( '(\d+)', s.rstrip() )
    for i in range(1, len(elements), 2):
        elements[i]=int(elements[i])
    return elements

for l in sorted(sys.stdin, key=sortable_list):
    sys.stdout.write(l)

Afterwards, use it to sort filenames. It looks like this:

=$ ls -1
a
i_1
i_10
i_15
i_20
i_8
i_9
k
m

=$ ls -1 | human_sort 
a
i_1
i_8
i_9
i_10
i_15
i_20
k
m
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top