PowerShell: how to sort a text file by column?

I want to sort a text file in PowerShell. The text file is as follows:

name1 4
name2 2.3
name3 6.7
name4 5.1

I want to output this file as follows:

name3 6.7
name4 5.1
name1 4
name2 2.3

As you can see, it is ordered in descending order of the number associated with the name. How to do it?

+5
source share
2 answers

You can sort by expression, split each line (space delimiter), discard the last element in system.double and sort by it:

Get-Content .\file.txt | Sort-Object { [double]$_.split()[-1] } -Descending
+6
source

another variant:

gc c:\f1.txt | add-member scriptproperty sortby {$this.split()[-1]} {[double]$this} -pass | sort sortby -desc
0
source

All Articles