powershell - Re-format numerous dates (each different) in .txt file -


i have numerous .txt files output handle.exe run of several days. need reorganize data relational database. first thing need dates re-formatted.

each file has in excess of 800 dates, disbursed unevenly throughout file. dates formatted:

june 29, 2016 12:05:45 pm , need 06-29-16 12:05:45.

i'm working on single file now, things dialed in. i've tried replace dates in situ (using array original dates) get-date , got nowhere. tried -replace , didn't work.

i've spent 3 or 4 days on , think i've broken head. i've tried many permutations of stuff don't know anymore.

the last thing tried below. attempt use hashtable, old date , new date in table.

##to set "|" separator arrays $ofs = '|'  ##to original dates array $a = @(sls .\hp.txt -pattern '(june 29|june 30|july 1|july 2|july 3|july 4)' | select -expandproperty line)  ##to dates corrected format array $b = @($a | foreach {$_ | get-date -format "mm-dd-yy hh:mm:ss"})  ##to old , new dates hash table $dates = @{$a = $b}  ##to bring in content file $file = (get-content c:\hp.txt)  ##to replace "name" "value" hash table file foreach ($d in $dates) {   $file = $file -replace $d.name, $d.value }  ##to save corrected file new file name set-content -path c:\hpnew.txt -value $file 

the $a array contains (in small part):

june 29, 2016 12:04:51 pm june 29, 2016 12:05:58 pm june 29, 2016 12:07:00 pm [note: lots more dates here] june 30, 2016 12:01:17 june 30, 2016 12:02:19 june 30, 2016 12:04:22 [note:continuing end]

the $b array contains:

06-29-16 12:04:51 06-29-16 12:05:58 06-29-16 12:07:00 [note: lots more dates ] 06-30-16 12:01:17 06-30-16 12:02:19 06-30-16 12:04:22 [note: continuing end]

there simpler, more elegant solution. help/direction great.

use regular expression extract date strings text, pass matches callback function parse them actual datetime values , format according requirements:

$re = '((?:january|february|...|december) \d{1,2}, \d{4} \d{1,2}:\d{2}:\d{2} [ap]m)'  $input_fmt  = 'mmmm d, yyyy h:mm:ss tt' $output_fmt = 'mm-dd-yy hh:mm:ss' $culture    = [globalization.cultureinfo]::invariantculture $options    = [text.regularexpressions.regexoptions]::ignorecase  $callback = {   [datetime]::parseexact($args[0].groups[1].value, $input_fmt, $culture).tostring($output_fmt) }  $txt = get-content '.\hp.txt' -raw [regex]::replace($txt, $re, $callback, $options) | set-content '.\hpnew.txt' 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -