5

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?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Locosantez
  • 55
  • 1
  • 1
  • 4

2 Answers2

8

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
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
0

another variant:

gc c:\f1.txt | add-member scriptproperty sortby {$this.split()[-1]} {[double]$this} -pass | sort sortby -desc
walid2mi
  • 2,704
  • 15
  • 15