我有一个像这样的文本文件:
Data I'm NOT looking for
More data that doesn't matter
Even more data that I don't
&Start/Finally the data I'm looking for
&Data/More data that I need
&Stop/I need this too
&Start/Second batch of data I need
&Data/I need this too
&Stop/Okay now I'm done
Ending that I don't need 这里是输出所需的内容:
File1.txt
&Start/Finally the data I'm looking for
&Data/More data that I need
&Stop/I need this too File2.txt
&Start/Second batch of data I need
&Data/I need this too
&Stop/Okay now I'm done 我需要对文件夹中的每个文件执行此操作(有时需要过滤多个文件)。文件名可以递增: ex。File1.txt,File2.txt,File3.txt。
这是我在没有运气的情况下尝试的:
ForEach-Object{
$text -join "`n" -split '(?ms)(?=^&START)' -match '^&START' |
Out-File B:\PowerShell\$filename}谢谢!
发布于 2016-10-25 12:45:40
看起来很接近:您的代码正确地提取了感兴趣的段落,但是没有对非&-starting行进行段内过滤,您需要写入特定于段落的输出文件:
$text -join "`n" -split '(?m)(?=^&Start)' -match '^&Start' |
ForEach-Object { $ndx=0 } { $_ -split '\n' -match '^&' | Out-File "File$((++$ndx)).txt" }这将为感兴趣的每一段创建顺序编号的文件,从File1.txt开始。
要对文件夹中的每个文件执行此操作,在所有输入文件中使用固定的命名方案File<n> (从而进行累积编号),并使用输出文件名:
Get-ChildItem -File . | ForEach-Object -Begin { $ndx=0 } -Process {
(Get-Content -Raw $_) -split '(?m)(?=^&Start)' -match '^&Start' |
ForEach-Object { $_ -split '\n' -match '^&' | Out-File "File$((++$ndx)).txt" }
}要对文件夹中的每个文件执行此操作,基于输入文件名和每个输入文件编号的输出文件名(PSv4+,由于使用-PipelineVariable):
Get-ChildItem -File . -PipelineVariable File | ForEach-Object {
(Get-Content -Raw $_) -split '(?m)(?=^&Start)' -match '^&Start' |
ForEach-Object {$ndx=0} { $_ -split '\n' -match '^&' | Out-File "$($File.Name)$((++$ndx)).txt" }
}发布于 2016-10-25 14:41:45
你发布了第二个问题(违反规则),它被删除了,但这是我的快速回答。我希望它能帮助你,让你更好地理解PS的工作原理:
$InputFile = "C:\temp\test\New folder (3)\File1.txt"
# get file content
$a=Get-Content $InputFile
# loop for every line in range 2 to last but one
for ($i=1; $i -lt ($a.count-1); $i++)
{
#geting string part between & and / , and construct output file name
$OutFile = "$(Split-Path $InputFile)\$(($a[$i] -split '/')[0] -replace '&','').txt"
$a[0]| Out-File $OutFile #creating output file and write first line in it
$a[$i]| Out-File $OutFile -Append #write info line
$a[-1]| Out-File $OutFile -Append #write last line
}发布于 2016-10-25 13:25:21
像这样吗?
$i=0
gci -path "C:\temp\ExplodeDir" -file | %{ (get-content -path $_.FullName -Raw).Replace("`r`n`r`n", ";").Replace("`r`n", "~").Split(";") | %{if ($_ -like "*Start*") {$i++; ($_ -split "~") | out-file "C:\temp\ResultFile\File$i.txt" }} }https://stackoverflow.com/questions/40239309
复制相似问题