在 .txt 文件中重新格式化多个日期(每个日期不同)

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

我有许多 .txt 文件是 handle.exe 运行 几天的输出。我需要重新组织数据以将其放入关系数据库中。我需要做的第一件事是重新格式化日期。

每个文件都有超过 800 个日期,在整个文件中分配不均。日期格式为:

June 29, 2016 12:05:45 PM 我需要 06-29-16 12:05:45.

我现在只处理一个文件,以便拨入内容。我尝试用 Get-Date 替换原位日期(使用数组作为原始日期)并得到无处。然后我尝试了 -replace 但没有用。

我已经为此花了 3 或 4 天时间,我想我已经崩溃了。我已经尝试了很多东西的排列,以至于我什至不知道我在哪里了。

我最后尝试的是下面的内容。尝试使用散列 table,在 table.

中包含旧日期和新日期
##To set "|" as separator for arrays
$OFS = '|'

##To get original dates into array
$a = @(sls .\hp.txt -pattern '(june 29|june 30|july 1|july 2|july 3|july 4)' | select -ExpandProperty line)

##To get dates with corrected format into array
$b = @($a | foreach {$_ | Get-Date -Format "MM-dd-yy hh:mm:ss"})

##To get old and new dates into hash table
$dates = @{$a = $b}

##To bring in content from file
$file = (Get-Content C:\hp.txt)

##To replace "NAME" with "VALUE" from hash table into file
foreach ($d in $dates) {
  $file = $file -replace $d.Name, $d.Value
}

##To save corrected file with new file name
Set-Content -Path C:\hpnew.txt -Value $file

$a数组包含(小部分):

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 AM
June 30, 2016 12:02:19 AM
June 30, 2016 12:04:22 AM
[NOTE:CONTINUING TO END]

$b数组包含:

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 TO END]

可能有更简单、更优雅的解决方案。但是任何 help/direction 都会很棒。

使用正则表达式从您的文本中提取日期字符串,然后将匹配项传递给回调函数,您 parse them to actual DateTime values and format 根据您的要求:

$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'