BUG
BUG

Reputation: 1

String manipulation while parsing CSV

The third column of a CSV file is as like this Every Monday 12am-2am of a CSV file.

ACB;Third Week;Every Monday 12am-2am
XYZ;Third Week;Every Tuesday 8pm-10pm

I would like to capture only 12am and 8pm and so on until the end of the csv file and write the details to a separate CSV file the complete output, like below.

ACB;12am
XYZ;8pm

Upvotes: 0

Views: 48

Answers (1)

vonPryz
vonPryz

Reputation: 24071

Use calculated properties extract a modified part of the data. The idea is to use Select-Object to select and modify the data like so,

select code, @{name="day";expression={ if($_.day -match "\d{1,2}[ap]m") {$Matches[0]} }}

So what's going on? The select (shorthand for Select-Object) can use a script block as an expression for processing. The argument is a hash table that contains manipulated property's name as a data source and expression that does stuff to it. The part if($_.day -match "\d{1,2}[ap]m") {$Matches[0]} checks if the day column value matches a regex for 1 or 2 digits followed by am or pm.

As for more complete an example,

$data = @'
ACB;Third Week;Every Monday 12am-2am
XYZ;Third Week;Every Tuesday 8pm-10pm
'@
$c = ConvertFrom-Csv -InputObject $data -Delimiter ";" -Header @('code','week','day')
$c | select code, @{name="day";expression={ if($_.day -match "\d{1,2}[ap]m") {$Matches[0]} }}
# Output
code day
---- ---
ACB  12am
XYZ  8pm

Upvotes: 1

Related Questions