Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: How do I sort a text file by column?

I want to sort a text file in PowerShell. The text file looks like this:

name1 4
name2 2.3
name3 6.7
name4 5.1

I want to output that file like this:

name3 6.7
name4 5.1
name1 4
name2 2.3

As you can see, it is ordered descending by the number associated to the name.How do I do that?

like image 979
Locosantez Avatar asked Apr 21 '12 14:04

Locosantez


1 Answers

You can sort by an expression, split each line (space delimiter), cast the last item to system.double and sort on it:

Get-Content .\file.txt | Sort-Object { [double]$_.split()[-1] } -Descending
like image 61
Shay Levy Avatar answered Sep 30 '22 13:09

Shay Levy