Sort file names function for Mac
There’s a known bug in OSx: when you get files by script, their order is messed.
I don’t remember the exact version number when it started, but I remember I had read a post about this issue on the Adobe scripting forum, but it was lost after Adobe destroyed the old forum.
Also, I encountered it myself while debugging a script a year or two ago. But then I had no time to find a solution and switched to PC.
Note: this is a bug with OSx — not the script!
Here is a solution I found on the forum:
The author is Uwe
Laubender
function SortFileNames(a, b) {
a = a.name;
b = b.name;
var regExp = new RegExp("^\\d+");
var aObj = {num: a.match(regExp) != null ? a.match(regExp)[0] : "_", string: a.replace(/^\d+/, "")};
var bObj = {num: b.match(regExp) != null ? b.match(regExp)[0] : "_", string: b.replace(/^\d+/, "")};
// a and b are fully numeric :
if (aObj.string =="" && bObj.string == "") { return a - b };
// the numeric parts of a and b are equal :
if (aObj.num == bObj.num ) { return aObj.string.toLowerCase() > bObj.string.toLowerCase() };
if (aObj.num > bObj.num ) { return 1 };
}
main();
function main() {
var folder = new Folder("~/Desktop/My Scripts");
var filesUnsorted = folder.getFiles();
var filesSorted = filesUnsorted.sort(SortFileNames);
}
I used it while updating the Create a book from InDesign documents in selected folder script.
