【问题标题】:Re-format numerous dates (each different) in .txt file在 .txt 文件中重新格式化多个日期(每个不同的日期)
【发布时间】:2016-08-09 07:15:14
【问题描述】:

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

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

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

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

我在这上面花了 3 或 4 天,但我想我的脑袋坏了。我已经尝试了很多东西的排列方式,以至于我现在都不知道自己在哪里了。

我尝试的最后一件事是在下面。尝试使用哈希表,表中包含旧日期和新日期。

##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 数组包含(一小部分):

2016 年 6 月 29 日 12:04:51 PM
2016 年 6 月 29 日 12:05:58 下午
2016 年 6 月 29 日 12:07:00
[注意:这里有更多日期]
2016 年 6 月 30 日 12:01:17
2016 年 6 月 30 日 12:02:19
2016 年 6 月 30 日 12:04:22
[注意:继续结束]

$b 数组包含:

06-29-16 12:04:51
06-29-16 12:05:58
06-29-16 12:07:00
[注意:更多日期]
06-30-16 12:01:17
06-30-16 12:02:19
06-30-16 12:04:22
[注意:继续结束]

可能有一个更简单、更优雅的解决方案。但任何帮助/指导都会很棒。

【问题讨论】:

  • 如果你可以安装 PS v5 你可以试试 - Convert-FromString powershellmagazine.com/2014/09/09/…
  • 基兰...谢谢你的小费。但是在 4.0 中真的没有办法做到这一点吗?哈希表会不起作用吗?看起来我已经接近了,但我无法做出最后的调整来让它踢出我想要的结果。

标签: powershell powershell-4.0


【解决方案1】:

使用正则表达式从文本中提取日期字符串,然后将匹配项传递给回调函数,您可以在其中将 parse 它们传递给实际的 DateTime 值和 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'

【讨论】:

  • 嗯,当我按照书面方式运行时,我得到了错误,“使用“3”参数调用“ParseExact”的异常:“字符串未被识别为有效的日期时间。 “
  • 您确实将 $re 中的省略号 (...) 替换为其他月份名称,用竖线 (|) 分隔,不是吗?
  • @Ansgar...不!我没有!大声笑,完全是我的错。你的意思是每件小事都必须是正确的?! [笑话] 效果很好。谢谢,谢谢,谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 2012-06-22
  • 1970-01-01
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
相关资源
最近更新 更多