Regex 如何在使用正则表达式和PowerShell拆分大型txt文件时包含关键字行上方的一行
我们有一个大的txt文件(“C:\temp\longmessages.txt”),如下所示: 美洲 这是开始 一些文本1 一些文本2 一些文本3 等等等等 结束 欧洲 这是开始 一些文本4 一些文本5 一些文本6 一些文本7 等等等等 结束 亚洲 这是开始 一些文本8 一些文本9 一些文本10 等等等等 结束 通过使用下面的PS脚本,我能够将C:\temp\longmessages.txt“拆分为较小的1.txt、2.txt、3.txt等。每个较小的.txt文件从第一个“开始”拆分到下一个“开始”,但是每个较小的文件都从“开始”开始,并在的“这是开始”上方留下一行而我们希望在每个较小的拆分文件顶部的“开始”上方包含一行,表示美洲、欧洲等。需要在“开始”上方的每个文件中添加Regex 如何在使用正则表达式和PowerShell拆分大型txt文件时包含关键字行上方的一行,regex,powershell,powershell-2.0,powershell-3.0,powershell-4.0,Regex,Powershell,Powershell 2.0,Powershell 3.0,Powershell 4.0,我们有一个大的txt文件(“C:\temp\longmessages.txt”),如下所示: 美洲 这是开始 一些文本1 一些文本2 一些文本3 等等等等 结束 欧洲 这是开始 一些文本4 一些文本5 一些文本6 一些文本7 等等等等 结束 亚洲 这是开始 一些文本8 一些文本9 一些文本10 等等等等 结束 通过使用下面的PS脚本,我能够将C:\temp\longmessages.txt“拆分为较小的1.txt、2.txt、3.txt等。每个较小的.txt文件从第一个“开始”拆分到下一个“开始
继续我的评论,我认为在写着
End
的行上进行拆分要容易得多
试一试
使用您的示例,这将生成三个文件:
1.txt
$InputFile = "C:\temp\longmessages.txt"
$Reader = New-Object System.IO.StreamReader($InputFile)
$a = 1
While (($Line = $Reader.ReadLine()) -ne $null) {
**If ($Line -match "START")** {
$OutputFile = "C:\temp\output\$a.txt"
$filename
if ($filename -eq $null){
$OutputFile = $filename
}
$a++
}
Add-Content $OutputFile $Line
}
Americas
This is Start
some text 1
some text 2
some text 3
etc. etc
End
Europe
This is Start
some text 4
some text 5
some text 6
some text 7
etc. etc
End
Asia
This is Start
some text 8
some text 9
some text 10
etc. etc
End
2.txt
$InputFile = "C:\temp\longmessages.txt"
$Reader = New-Object System.IO.StreamReader($InputFile)
$a = 1
While (($Line = $Reader.ReadLine()) -ne $null) {
**If ($Line -match "START")** {
$OutputFile = "C:\temp\output\$a.txt"
$filename
if ($filename -eq $null){
$OutputFile = $filename
}
$a++
}
Add-Content $OutputFile $Line
}
Americas
This is Start
some text 1
some text 2
some text 3
etc. etc
End
Europe
This is Start
some text 4
some text 5
some text 6
some text 7
etc. etc
End
Asia
This is Start
some text 8
some text 9
some text 10
etc. etc
End
3.txt
$InputFile = "C:\temp\longmessages.txt"
$Reader = New-Object System.IO.StreamReader($InputFile)
$a = 1
While (($Line = $Reader.ReadLine()) -ne $null) {
**If ($Line -match "START")** {
$OutputFile = "C:\temp\output\$a.txt"
$filename
if ($filename -eq $null){
$OutputFile = $filename
}
$a++
}
Add-Content $OutputFile $Line
}
Americas
This is Start
some text 1
some text 2
some text 3
etc. etc
End
Europe
This is Start
some text 4
some text 5
some text 6
some text 7
etc. etc
End
Asia
This is Start
some text 8
some text 9
some text 10
etc. etc
End
那为什么不在
“END”
处拆分呢?这太完美了,谢谢!