powershell - 过滤数据部分,包括起始行和结束行 - PowerShell

标签 powershell powershell-4.0

我有一个如下所示的文本文件:

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  

以下是输出需要的内容:

文件1.txt

&Start/Finally the data I'm looking for  
&Data/More data that I need   
&Stop/I need this too  

文件2.txt

&Start/Second batch of data I need  
&Data/I need this too 
&Stop/Okay now I'm done  

我需要对文件夹中的每个文件执行此操作(有时需要过滤多个文件。)文件名可以递增:例如。文件1.txt、文件2.txt、文件3.txt。

这是我尝试过但没有成功的方法:

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

谢谢!

最佳答案

看起来您非常接近:您的代码正确提取了感兴趣的段落,但段内过滤了非 & - 缺少起始行,您需要写入特定于段落的输出文件:

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

关于powershell - 过滤数据部分,包括起始行和结束行 - PowerShell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239309/

相关文章:

windows - PowerShell 从命令行参数中去除双引号

windows - 如何使用 PowerShell 获取远程计算机的可用物理内存

powershell - 如何避免 PowerShell 内联文档中的换行符

powershell - 在 PowerShell 作业中使用本地函数

loops - 如何打破 Powershell 中的 Foreach 循环?

解压缩时powershell空值表达式错误

powershell - 如何使用 PowerShell v4 将成员从一个安全组复制到 AD 中的另一个安全组?

powershell - PowerShell:控制台应用程序的远程执行失败

powershell - 通过 Powershell 获取 Google 搜索结果

powershell - 功能中的switch语句