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.
You can try this:
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:
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.
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
to print all the files with the largest one first, I'd be interested to see it.
I'm sure someone can do this better, but here is one way that is fully compatible with lynix. It has the benefit of leaving you with a reusable
rev
string function for your toolbox, i.e. it sorts the entire string and not just the last character:I think the foreach's here nicely demonstrate how PowerShell pipes are arrays and not simply strings like in *nix.
It took me a little while to realize that I had to use only
$_
and not$_.name
inside the 2ndforeach
. So I've learned something about variations in the array content from one pipe to the next.*Credit for the guts of my rev function goes to http://rosettacode.org/wiki/Reverse_a_string#PowerShell
Works like lynix:
Sort of works like lynix, but very, very slow:
Do not work like lynix, i.e. fail to sort all characters of the file names; (only sorts the very last character of the string):
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:
Also you can use the (abbreviated)
-Name
argument toGet-ChildItem
:which will return strings directly.
If you really want to sort by the reverse string, then the following works (but is slow):
You can make it faster if you have an upper bound on the file name's length.