我正在尝试获取特定的CSV列并以升序对其进行排序,但是由于某种原因,我得到的值都被弄乱了。例如,如果我的csv文件的第1列是3,5,1,6,3,我希望它以1,3,3,5,6的升序输出。
这就是我要尝试的:(我也尝试过不带-property)
$csvFile = Import-CSV <mypath>
$sortColumn = $csvFile.column1 | Sort-Object -Property {$_ -as [decimal]}
有没有快速的方法可以做到这一点?也许有一种方法可以将该列转换为数组然后对其进行排序?
答案 0 :(得分:0)
尝试
$_.yourcolumnname
而不是
$_
答案 1 :(得分:0)
虽然您的方法应该有效,但是假设您引用的是正确的列,则不会快速。
要获得更快的替代方法,请考虑以下问题:
# Simulate import of a CSV file.
$csvFile = @'
Num
3
5
1
6
3
'@ | ConvertFrom-Csv
# Convert the column values to an array of [decimal]s by way of a cast.
$nums = [decimal[]] $csvFile.Num
# Sort the array in place.
[Array]::Sort($nums)
# The above is the conceptual equivalent of the following, which is much slower:
# $nums = $csvFile.Num | Sort-Object { $_ -as [decimal] }
输出排序后的数组$nums
会产生:
1
3
3
5
6