TOGEEK
TOGEEK

Reputation: 741

Create an array from a CSV list

I have a list in orders.csv like so:

Order
1025405008
1054003899
1055003868
1079004365

I wish to add the unit number (2nd-4th chars) and the entire order number into an array, so it will be like:

"0254","1025405008"
"0540","1054003899"
etc
etc

I wish to ignore the prefix "1". So far, with my limited PS knowledge, I have created the variables:

$Orders = Import-csv c:\Orderlist.csv 
$Units = $Orders | Select @{LABEL="Unit";EXPRESSION={$_.Order.Substring(1,4)}}

So I wish to combine the two into an array. I have tried

$array = $Units,Orders

Any help will be appreciated.

Upvotes: 1

Views: 2352

Answers (2)

woxxom
woxxom

Reputation: 73506

In case of a big CSV file that has just this one column using regexp is much faster than Select:

$combined = [IO.File]::ReadAllText('c:\Orderlist.csv') `
    -replace '(?m)^\d(\d{4})\d+', '"$1","$&"' `
    -replace '^Order', 'Unit, Order' | ConvertFrom-Csv

~6x faster on 100k records in a 2MB file (700ms vs 4100ms)

Upvotes: 4

Martin Brandl
Martin Brandl

Reputation: 58931

You can just select the Order within your Select statement and use the ConvertTo-Csv cmdlet to get the desired output:

$Orders = Import-csv c:\Orderlist.csv
$unitOrderArray = $Orders | Select @{LABEL="Unit";EXPRESSION={$_.Order.Substring(1,4)}}, Order
$unitOrderArray | ConvertTo-Csv -NoTypeInformation

Output:

"Unit","Order"
"0254","1025405008"
"0540","1054003899"
"0550","1055003868"
"0790","1079004365"

Upvotes: 3

Related Questions