Sorting a list of files in a folder...

Hi There,

Just wondered if someone could help me with a small query.

Up to a few months ago I was using the method below to retrieve a list of files in a folder and I used the Finder to sort it by name.

tell application "Finder"
	set thisFolder to choose folder with prompt "Choose the folder containing the PDFs to rename:"
	set theItems to every file of thisFolder
	
	set theItems to (theItems sort by name)
end tell

I’ve recently been using set theItems to paragraphs of (do shell script "ls " & p) to get a folders contents which has worked fine apart from one slight niggle.
I realise the returned results are different in each method however, I wondered, what would be the best way to sort the returned list by name as in the above example?

If someone could give me some pointers I’d be grateful.

Thanks,

Nick

ls has a case sensitive sort by default but you can rearrange the items by using sort command

set theItems to paragraphs of (do shell script "ls " & quoted form of posix path of thisFolder & " | sort -f")

Thought this had worked but my mistake.

If I have 1000 files in a folder named file1, file2, file3 … file998, file999, file1000 etc, when using the ls command the returned list comes back file1, file11, file12, file13, file14 etc not file1, file2, file3, file4…
It’s not listed ‘naturally’ ?

Is there a way round this?

Thanks again,

Nick

Nick:

Given a simple list with a common nomenclature.
file 1.ai
file 2.ai
file 3.ai
file 4.ai
file 5.ai
file 6.ai
file 7.ai
file 8.ai
file 9.ai
file 10.ai
file 11.ai

An ls does return: file 1.ai file 11.ai, file 2.ai, etc.

If we push it into a ls | sort we get similar results: file 1.ai file 11.ai, file 2.ai, etc.

If we use a key on the sort (and this is where the common convention is necessary) we can sort on a given part of the return.
ls | sort -k2 -n returns: file 1.ai, file 2.ai, file 3.ai,. file 10.ai, etc.
List files | sort on the second key numerically. Optionally you could add -r to reverse the sort.

Hope that helps.

Cheers,
Jim
BLUEFROG

Thanks for the explanation Jim, it’s a big help.
The code works great. :slight_smile:

Thanks again for your time.

Nick

My pleasure, Nick. :slight_smile:

Jim