Sorting List with numbers

Hi! Running into a roadblock in a macro I'm making. I've generated a list of numerical values that i'd like to sort in ascending order, the filter Variable "Sort Lines" Sorts the list like this:


So in this case, the smallest number is at the top of the list, but it is only sorting "alphabetically" what's the correct way to sort truly by numerical value?

You should find various approaches here:

1 Like


can't seem to get anything on that thread to work. this seems relatively simple but every solution is a script in a language i don't understand so it's hard to see where i'm going wrong but i'll keep banging my head against it and see what i can do.

For example: This:
Outputs this:

When I type in a bunch of random numbers, it sorts it fine, but when I use the variable i'm generating it just doesn't sort them.

Alright, something funky is going on, when i just type these same numbers in, it's sorting correctly, so i'm guessing it's something in my variable that isn't visible, maybe the %Return% token?

Seems that was the culprit, although I don't really understand WHY, adding this action fixed the sort:

For example:
Numeric sorting.kmmacros (2.0 KB)

Can you post the relevant part(s) of the macro? That'll help us see what's happening (this...

Sort Test.kmmacros (3.5 KB)

Image for me, anything else is guesswork).

Edit to add...

How are you populating PotentialMarkerList? sort sorts by line but expects Unix line endings -- if you're providing old-style Mac or (shudder) Windows line endings it'll think it is just one line of text, nothing to sort.

I'm populating with this action (which is inside a for loop)

So any bash command that would act on a list, i'd need to specify unix line endings, rather than what keyboard maestro generates with the %Return% token?

A little demo macro:

Line Feed Test.kmmacros (4.0 KB)


Run it and you'll see that "typed returns" in a text box are ASCII character 10 while %Return% tokens give old-style Mac carriage returns of ASCII character 13. So yes, you'll need to keep that in mind and make sure things get what they expect.

You can use typed returns in the "Append" action, use the %Return% token and then filter as you did or use tr as in the demo, and there's plenty more ays of dealing with it. Do remember that text sent back from the "Shell" action will now have Unix line endings -- most apps will be happy with those but you will get caught out occasionally.

1 Like

Appreciate the explanation / demo. I don't think i grasp the reason why these differences exist, but I do understand THAT they exist and why my macro wasn't working and how to avoid it in the future!

Forgot to mention -- when you want to use Unix line endings and don't want to type Returns in the text box, use \n. You can also use these in a "Search and Replace" action eg search for \n, replace with \r to go from Unix to old-Mac line endings.

1 Like