1

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.

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

4 Comments

What does $& stand for in the replacement? I've never seen that before.
Part of the original string that matches the entire pattern.
Wow, how did I missed that? I always used nested capture groups to achieve this. Nice one!
3

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"

1 Comment

Hah! That easy (when you know how!). Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.