dazedandconfused
dazedandconfused

Reputation: 85

Extracting values from strings in an array using powershell

I've got an issue trying to extract particular values from an Array. I have an array that contains 40010 rows each of which is a string of pipe separated values (64 on each line).

I need to extract values 7, 4, 22, 23, 24, 52 and 62 from each row and write it into a new array so that I will end up with a new array containing 40010 rows with only 7 pipe separated values in each (could be comma separated) row.

I've looked at split and can't seem to get my head around it to even get close to what I need.

I'd also be open to doing this from a file as I'm currently creating my 1st array with
$data = (Get-content $statement_file|Select-String "^01")

If I can add to that command to do the split on the input so I only have one array and don't need the intermediate array that would be even better.

I know if I was in Linux I could do the split with AWK quite easily but I'm fairly new to powershell so would appreciate any suggestions

Upvotes: 1

Views: 2287

Answers (1)

TechSpud
TechSpud

Reputation: 3518

# create an array of header columns (assuming your pipe separated file doesn't have headers)
$header = 1..64 | ForEach-Object { "h$_" }

# import the file as 'csv' but with pipes as separators, use the above header, then select  columns 7,4,22,23,24,52,62
# edit 1: then only return rows that start with 01
# edit 2: then join these into a pipe separated string
$smallerArray = $statement_file |
    Import-Csv -Delimiter '|' -Header $header |
    Where-Object { $_.h1.StartsWith('01') } |
    Select-Object @{Name="piped"; Expression={ @($_.h7,$_.h4,$_.h22,$_.h23,$_.h24,$_.h52,$_.h62) -join '|' }} |
    Select-Object -ExpandProperty piped

Upvotes: 4

Related Questions