简体   繁体   中英

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?

您可以按表达式排序,分割每行(空格分隔符),将最后一项转换为system.double并对其进行排序:

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

另一个变体:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM