2016-10-25 19 views
2

我有一个文本文件,它看起来像这样:滤波部分,包括起点和终点的线 - PowerShell的

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 

我需要为文件夹中的所有文件(有时会出现,这将需要过滤多个文件)的文件名可以增加这样做:恩。 File1.txt,File2.txt,File3.txt。

这是我已经没有运气尝试:

ForEach-Object{ 
$text -join "`n" -split '(?ms)(?=^&START)' -match '^&START' | 
Out-File B:\PowerShell\$filename} 

谢谢!

回答

1

看起来你是非常接近:你的代码正确提取的感兴趣的段落,但非& -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" } 
} 
+1

完美地工作。谢谢!!! – red2015

0

像这样?

$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" }} } 
1

您发布第二个问题(违反规则),它被删除,但这是我的快速回答。我希望它能帮助你,让你更有意识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 
    } 
+0

我不知道这是违反规则在这个论坛上发布多个问题。抱歉。 – red2015

+0

把“我有苹果​​,想要馅饼”这样的问题声音放在规则上是违反规定的。您需要更加详细,添加您的代码并提出更具体的问题,而不是一般问题。 – autosvet

+0

好吧,很酷。感谢回复。 – red2015

相关问题