19

I am trying to sort a colomn with numbers in a CSV file. But somehow it doesn't work. Sample CSV:

Orange;65
Red;160
Green;140
White;110
Purple;85

This is the piece of code I tried it with:

$csv = Import-Csv -Header "Color", "Number" -delimiter ';' data.csv
$csv | Sort-Object Number

Which gives me the following output:

Color                Number
-----                ------
White                110
Green                140
Red                  160
Orange               65
Purple               85

Obviously not in the correct order. Can someone please explain me how to resolve this issue?

4

1 回答 1

45

Import-CSV imports csv columns as strings by default. You need to cast it to int before you can sort by value, and not "alphabetical". Ex:

$csv = Import-Csv -Header "Color", "Number" -delimiter ';' data.csv
$csv | % { $_.Number = [int]$_.Number }
$csv | Sort-Object Number

Color  Number
-----  ------
Orange     65
Purple     85
White     110
Green     140
Red       160

As an alternative, you can cast it while sorting, like this:

$csv = Import-Csv -Header "Color", "Number" -delimiter ';' data.csv
$csv | Sort-Object @{e={$_.Number -as [int]}}

or even shorter $csv | Sort-Object { [int]$_.Number }

于 2013-02-23T12:31:15.193 回答