【问题标题】:Powershell string parsing. Pull the date from a string of textPowershell 字符串解析。从一串文本中提取日期
【发布时间】:2019-10-23 04:44:20
【问题描述】:

我有一个(纯文本)日志文件,其中包含出现在大多数(但不是全部)文本行中的日期。日期并不总是出现在每一行的相同位置。尽管并非所有行都有日期,但在任何给定的 10 行中总是有一个日期。日志样本:

03/05/2019 Event A occurred
03/05/2019 Event B occurred
Event B Details: Details Details
03/07/2019 Event C occurred
Logging completed on 03/08/2019
03/08/2019 Event D occurred

我需要获取上次记录的日期。我不需要该行的内容,只需要该行中的日期。

#Get the log file. Tail it because it's huge. The regex pattern matches date format dd/mm/yyyy.
$log = (Get-Content -tail 10 C:\mylog.log | Select-String -Pattern "\d{2}/\d{2}\/d{4}"
#Get the last item in the $log variable. Convert it to a string.
$string = $log[-1].toString()

#Split the string. Match each element to a date format. 
#When an element matches a date format, assign its value to a DateTime variable.
foreach ($s in $string.split() ){
    if ($s -match "\d{2}/\d{2}\/d{4}"){
        [DateTime]$date = $s
        }
    }
"The last entry in the log was made on $date"

这段代码的两部分(查找带有日期的最后一行,并从行中提取日期)看起来非常笨拙。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: powershell parsing


    【解决方案1】:

    您可以执行以下操作:

    [datetime]((Get-Content mylog.log -tail 10) |
      Select-String '\d{2}/\d{2}/\d{4}')[-1].Matches.Value
    

    Select-String 返回一个集合 MatchInfo 对象。每个对象的.Matches.Value 都包含匹配的字符串。使用[-1] 索引,我们可以抓取最后一个对象。

    注意: Select-String 有一个可以读取文件的-Path 参数。但考虑到您不想阅读整个文件,则使用Get-Content -Tail

    【讨论】:

    • 谢谢。这正是我一直在寻找的:更紧凑,但仍然可读(似乎经常在两者之间进行权衡)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2021-09-25
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    相关资源
    最近更新 更多