Powershell 解析日志文件并在丢失时添加时间戳

问题描述 投票:0回答:1

给定一个这样的日志文件:

10:36:36:891 blah blah 1
10:36:36:891 blah blah 2
  blah blah 3
10:37:00:231 blah blah 4

我想解析日志文件,查看每一行以确定是否有时间戳。如果没有,请将前一个时间戳添加(前置)到该行并继续转到下一行,然后最终保存包含更改的日志文件。

我是 PowerShell 新手,但可能需要从以下内容开始:

foreach($line in Get-Content .\file.txt)
 if($line -match $regex){
   # Work here
  }
 }
powershell replace timestamp edit
1个回答
0
投票

这假定行开头的时间戳采用特定格式。

foreach ($line in (Get-Content .\file.txt)) {
    if ($line -match '^(\d{2}:\d{2}:\d{2}:\d{3}).*') {
        Write-Host "The timestamp is $($Matches[1])"
    }
}

是否需要将时间戳转换为

[datetime]
对象?

© www.soinside.com 2019 - 2024. All rights reserved.