PowerShell sorting problem of decimal numbers

冷暖自知 提交于 2020-12-13 04:25:26

问题


I have an array with decimal numbers like this:

reihenfolge
###########
100000.00001
1000000.00001
101000.00001
101010.00001
101020.10001

If I sort it without parameters I get the order above. I would expect that the second number is the last entry. I also tried to sort as int or as version or with regex, but until now I didn't find the way I expect.

$script:array = $script:array | Sort-Object reihenfolge

$script:array = $script:array | Sort-Object { [regex]::Replace($_.reihenfolge, '\d+', { $args[0].Value.PadLeft(20) }) }

$script:array = $script:array | Sort-Object { $_.reihenfolge -as [version] }

$script:array = $script:array | Sort-Object { $_.reihenfolge -as [int] }

回答1:


It looks like you are reading the array from a text or csv file. In that case, the numbers are actually strings, not numbers. In order to sort numeric, try below:

1) If your array comes from a textfile, INCLUDING the lines reihenfolge and ########### use the Get-Content cmdlet:

$array = Get-Content -Path 'D:\blah.txt' | Select-Object -Skip 2 | Sort-Object @{Expression = { [double]$_ }}
$array

2) If your data comes from a CSV file with a column named reihenfolge, do this:

$array = (Import-Csv -Path 'D:\blah.txt').reihenfolge | Sort-Object @{Expression = { [double]$_ }}
$array

Both will return the array sorted like this:

100000.00001
101000.00001
101010.00001
101020.10001
1000000.00001


来源:https://stackoverflow.com/questions/57991756/powershell-sorting-problem-of-decimal-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!