我有一个非常大的日志文件,我想搜索。一些长线分为两行。我想取这些行的第二行并将它连接到前一行,这样它们就会再次出现在同一行。
该文件如下所示:
05/10 some text
05/10 some text
05/10 some text
05/10 some really long text that goes to
the second line
05/10 some text
05/10 some text
05/10 some really long text that goes to
the second line
我希望文件看起来像这样:
05/10 some text
05/10 some text
05/10 some text
05/10 some really long text that goes to the second line
05/10 some text
05/10 some text
05/10 some really long text that goes to the second line
答案 0 :(得分:0)
这样做的框架非常简单。迭代输出的行,当需要组合时,在继续之前连接它们。
$collector = $null
@(switch -file $filename {
{ isNewLine($_) } {
# Start of new line.
# Output the current collector, and reinitialize with the new line.
$collector
$collector = $_
}
default {
# Continuation of previous line. Add current to collector.
$collector += $_
}
}, $collector) | Out-File $outputFile
棘手的部分是如何定义函数isNewLine
。例如,如果“好”行始终以文本05/10
开头,则可以使用:
function isNewLine([string]$line) {
$line.startsWith('05/10')
}
或者更一般地说,如果它始终以MM/dd
形式的日期开头,则可以使用正则表达式。
function isNewLine([string]$line) {
$line -match '^\d{2}/\d{2}'
}
如果您需要检查行的结尾而不是开头,结构会略有不同。例如,如果任何长于80个字符的行与下一行
组合在一起$collector = $null
@(switch -file $filename {
{ $_.length -ge 80 } {
# Line continues on next. Save to collector
$collector += $_
}
default {
# Line doesn't continue. Output it and clear collector
$collector + $_
$collector = $null
}
}, $collector) | Out-File $outputFile