Powershell challenge
Solution 1:
You can try this:
dir| sort {$_.name[-1]}
Solution 2:
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.
Solution 3:
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.
Solution 4:
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:
function rev ($s) {return -join ($s[$s.Length..0])}
dir | foreach{rev($_.name)} | sort | foreach{rev($_)}
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 2nd foreach
. 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:
- dir | sort -Property @{Expression ={$n = $_.Name.ToCharArray(); [Array]::Reverse($n);[String]::Join("",$n)}}
Sort of works like lynix, but very, very slow:
- ls -n|sort{$_[3e3..0]}
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):
- dir| sort {$.name.Substring($.name.length-1)}
- dir| sort {$_.name[-1]}
- ls|sort{$_.Name[-1]}
- ls|sort{"$_"[-1]}
- ls -n|sort{$_[-1]}