Notifications
Clear all

[Closed] Sorting by filename

Hello.
I want to write a function that looks through all subfolders of a specified folder that contain a .max file and prints out all the max files’ locations, but sorted by the name of the max file itself and not the directory. So if an array contained “D:\Test\Folder1\object2.max” & “D:\Test\Folder2\object1.max” it would print out first the second and then the first.

I’m not a programmer and I can’t figure out for the life of me how to approach this. I tried dozens of messy solutions and I can’t even get to a part where I get a list of the files themselves to sort. Here is one of my attempts, but even it doesn’t do its job right because when I run it in a directory with lots of subfolders it returns something like this for each item:

“Sub1\Sub2\Obj1.max”
“Sub2\Obj1.max”
“Obj1.max”

fn getFilesRecursive root =
(
dir_array = GetDirectories (root+"/*")
for d in dir_array do join dir_array (GetDirectories (d + "/*"))
my_files = #()
for f in dir_array do join my_files (getFiles (f + "*.max"))
my_array = #()
for a in my_files do
	(
	for b in dir_array do
		(
		if (matchPattern a pattern:((b as string) + "*")) == true then 
			(
			s1 = substituteString a b ""
			append my_array s1
			sort my_array
			)
		)
	)
print my_array
)
getFilesRecursive "D:\Test"

Any help would be greatly appreciated!

3 Replies

There are different ways of doing it. One could be the following:

(
 
 	fn GetFilesRecursive root =
 	(
 		folders = getdirectories (root+"/*")
 		for j in folders do join folders (getdirectories (j+"/*"))
 		files = #()
 		for j in folders do
 		(
 			for k in (getfiles (j + "*.max")) do append files #(k, tolower (filenamefrompath k))
 		)
 		return files
 	)
 	
 	fn SortFilesByFilename n1 n2 =
 	(
 		if n1[2] < n2[2] then -1 else if n1[2] > n2[2] then 1 else 0
 	)
 	
 	
 	fn GetSortedMaxFilesInFolder root =
 	(
 		files = GetFilesRecursive root
 		qsort files SortFilesByFilename
 		files = for j in files collect j[1]
 		return files
 	)
 
 	files = GetSortedMaxFilesInFolder @"D:\Test"
 	print files
 	
 )

Note that there might be other solutions on this forum either in MXS or C#, but the above code seems to be not so bad. You may also add a sorting step for folders too.

Works like a charm Thank you very much for your help!

if filenames are strings in the same case the sorting function can be the built-in stricmp