tags:

views:

216

answers:

5

I've been challenged by a friend to do the following:

"Find the quickest and easiest way of sorting a directory listing by the LAST character of the filenames."

He's done it on Linux using the following:

ls | rev | sort | rev

I'd like to show him the powershell alternative, but I'm only just starting to learn powershell and I can't do it. So, I'm cheating and asking for your help.

+5  A: 

Unfortunately Powershell does not have a nice easy reverse method, so instead you have to get the last letter of the string and sort by that. This is one way i've done it:

dir| sort {$_.name.Substring($_.name.length-1)}

As has been pointed out, this will sort strictly by the last letter only, whereas I the Linux version will sort by the last and then subsequent letters, so there may be a better way of doing this, or you may have to introduce some looping if you want it that way.

Sam Cogan
That's brill. Not as short as the Linux alternative, but still pretty good.
Richard
I noticed too that this only sorts by the last letter, unlike the linux version. However the challenge stated "by the LAST character" so this answer answers the question, even if the two solutions aren't equal.
Richard
A: 
dir | sort -Property @{Expression ={$n = $_.Name.ToCharArray(); [Array]::Reverse($n);[String]::Join("",$n)}}


Not as short as the unix version, mostly because there isn't a String.Reverse() function in the .NET Framework. Basically this works by telling sort 'sort by computing this expression on the input arguments'.


Now, if any unix shell does better than

dir | sort -Property Length -Descending

to print all the files with the largest one first, I'd be interested to see it.

How about 'ls -S'?
Bryan
Wow! Didn't know about this one :D Nice one :)
AntonioCS
+4  A: 

dir| sort {$_.name[-1]}

Shay Levy
+3  A: 

Shay's variant is way shorter than the accepted answer by indexing into the string but even that can be improved. You can shorten it even more by excluding unnecessary spaces and using a shorter alias:

ls|sort{$_.Name[-1]}

Also you can use the (abbreviated) -Name argument to Get-ChildItem:

ls -n|sort{$_[-1]}

which will return strings directly.

If you really want to sort by the reverse string, then the following works (but is slow):

ls -n|sort{$_[3e3..0]}

You can make it faster if you have an upper bound on the file name's length.

Joey
Why can't you just call $_.Name.Length to get the length (i.e. ls -n|sort{$_[$_.Name.Length..0]}) ?
zdan
I could, but it would waste characters.
Joey
+5  A: 

Here's my entry:

ls | sort {"$_"[-1]}

and to get pathological:

ls|sort{"$_"[-1]}
Keith Hill
I tried code in each answer and they all work, but this one has the shortest syntax. I can't tell if one version is any faster than the others, which would require timing it on a folder with lots of files.
Bratch