我有一个构建日志,我想从中提取一些内容。我想从给定系统名称的日志文件中提取[xxxxcontentxxxx]
,如果有的话。
INPUT.TXT:
150755: CMDLINE=omake System1
150758: Subsystem Start: Tue Dec 22 03:33:06 2015 1450726386
[xxxxcontentxxxx]
151251: Subsystem End: Tue Dec 22 03:35:00 2015 1450726500
151255: CMDLINE=omake System2
151258: Subsystem Start: Tue Dec 22 03:35:00 2015 1450726500
151668: Subsystem End: Tue Dec 22 03:36:28 2015 1450726588
151672: CMDLINE=omake System3
151675: Subsystem Start: Tue Dec 22 03:36:29 2015 1450726589
[xxxxcontentxxxx]
152020: Subsystem End: Tue Dec 22 03:38:14 2015 1450726694
152024: CMDLINE=omake System4
152027: Subsystem Start: Tue Dec 22 03:38:15 2015 1450726695
[xxxxcontentxxxx]
152294: Subsystem End: Tue Dec 22 03:39:12 2015 1450726752
152298: CMDLINE=omake System5
152301: Subsystem Start: Tue Dec 22 03:39:12 2015 1450726752
[xxxxcontentxxxx]
152558: Subsystem End: Tue Dec 22 03:40:18 2015 1450726818
例如,我想提取System2,System3和System4。输出应按以下格式保存到文件中:
注意:系统2被跳过,因为它不包含[xxxxcontentxxxx]
Output.txt的:
151672: CMDLINE=omake System3
151675: Subsystem Start: Tue Dec 22 03:36:29 2015 1450726589
[xxxxcontentxxxx]
152020: Subsystem End: Tue Dec 22 03:38:14 2015 1450726694
152024: CMDLINE=omake System4
152027: Subsystem Start: Tue Dec 22 03:38:15 2015 1450726695
[xxxxcontentxxxx]
152294: Subsystem End: Tue Dec 22 03:39:12 2015 1450726752
如何使用PowerShell实现这一目标?
这是我的一切。当然,有一种更优雅的方式来实现这一目标:
$reader = [System.IO.File]::OpenText("C:\log.txt")
try {
$startPrinting = $false
for (;;) {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
if ($line.Split(' ').Contains("System2") -or
$line.Split(' ').Contains("System3") -or
$line.Split(' ').Contains("System4")
) {
$startPrinting = $true
}
if ($startPrinting) {
Write-Host $line
}
if ($line.split(' ').Contains('End:')) {
$startPrinting = $false
}
}
} finally {
$reader.Close()
}
答案 0 :(得分:0)
例如,您可以使用switch
语句,如下所示:
$systems = 'System2', 'System3', 'System4'
$reader = [IO.File]::OpenText('.\Documents\test.txt')
while ($line = $reader.ReadLine()) {
switch -regex ($line) {
'CMDLINE=omake (\S+)' {
$systemName = $matches[1]
$msg = @($line)
}
'Subsystem End' {
if ($systems -contains $systemName) {
if ($msg.Count -gt 3) {
$msg -join "`r`n"
} else {
"Note: $systemName is skipped because it doesn't have content."
}
}
}
default { $msg += $line }
}
}
$reader.Close()
这当然是完全未完成的,因为它假设您的输入文件始终以CMDLINE
行开头,以Subsystem End
行结束。但它应该给你一般的想法。