Using RegEx to sort text in a variable?

Bravo, Tom!

I should really have tested my proposed solution. As you pointed out, the period before the file extension makes it tricky. Periods (46) are farther down the ASCII list than a Space (32) so spaces take precedence in an ASCII sort.

For my punishment, I submit this macro to sort a selection of lines in a text editor. I didn't resort to the Schwartzian Transform, though. I just told old Unix sort to ignore case and use the period as a delimiter, sorting the first field (delimited by the period) and then sort the next field.

echo "$KMVAR_kmVar" | sort -f -t'.' -k1,1 -k1,2

There are some cases where you'd want to look past the first field (just add 'Water 06.jpg' to that list, for example). The ST solution fails there but this one handles that.

Sometimes it seems like every list needs custom code to sort. But I'm going to try using this macro generally for a while to see when it breaks. I'm sure it will. :persevere:

Anyway, I learned something following you on this topic and wanted to say thanks.

Sort Lines [test].kmmacros (5.6 KB)

2 Likes