如何在powershell中对CSV列进行排序?
我试图获取一个特定的CSV列并按升序进行排序,但由于某些原因,我得到的值都被弄乱了。例如,如果我的csv文件的第1列是3,5,1,6,3,我希望它以1,3,3,5,6的升序输出 这就是我正在尝试的:(我也尝试了不使用-property)如何在powershell中对CSV列进行排序?,powershell,csv,Powershell,Csv,我试图获取一个特定的CSV列并按升序进行排序,但由于某些原因,我得到的值都被弄乱了。例如,如果我的csv文件的第1列是3,5,1,6,3,我希望它以1,3,3,5,6的升序输出 这就是我正在尝试的:(我也尝试了不使用-property) $csvFile=导入CSV $sortColumn=$csvFile.column1 |排序对象-属性{$\-as[decimal]} 有什么快速的方法可以做到这一点吗?也许有办法将该列转换为数组,然后对其进行排序?试试看 $_.yourcolumnname
$csvFile=导入CSV
$sortColumn=$csvFile.column1 |排序对象-属性{$\-as[decimal]}
有什么快速的方法可以做到这一点吗?也许有办法将该列转换为数组,然后对其进行排序?试试看
$_.yourcolumnname
而不是
$_
试一试
而不是
$_
虽然您的方法应该有效,但假设您引用的是正确的列,它不会很快
<> P>对于一个更快的选择,考虑如下:
# 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.
虽然您的方法应该有效,但假设您引用的是正确的列,它不会很快
<> P>对于一个更快的选择,考虑如下:
# 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.
请注意,问题中的输入是$csvFile.column1
,即特定列的值。因此,问题中的代码应该按原样工作,假设.column1
值可以转换为[decimal]
——尽管它不会很好地执行。请注意,问题中的输入是$csvFile.column1
,即特定列的值。因此,问题中的代码应该按原样工作,假设.column1
值可以转换为[decimal]
——尽管它的性能不好。