Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort-Object and Integers

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?

like image 882
ScriptingBerry Avatar asked Feb 23 '13 12:02

ScriptingBerry


People also ask

What is Object in sorting?

An Object is an unordered collection of properties. The answers below show you how to "use" sorted properties, using the help of arrays, but never actually alter the order of properties of objects themselves.

Can we sort objects in JavaScript?

Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array of objects in PowerShell?

For example, with a hash table you can sort one property in ascending order and another property in descending order. To sort objects, send them down the pipeline to Sort-Object . If you use the InputObject parameter to submit a collection of items, Sort-Object receives one object that represents the collection.

How do you sort items in PowerShell?

To sort the output in the PowerShell you need to use Sort-Object Pipeline cmdlet. In the below example, we will retrieve the output from the Get-Process command and we will sort the, according to memory and CPU usage.


1 Answers

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 }

like image 192
Frode F. Avatar answered Oct 04 '22 07:10

Frode F.