2

我正在阅读很多线程 - 但对我个人而言没有任何内容。我需要以以下形式拆分文本文件:

---------------------  Instance Type and Transmission --------------    
...text..     
...text.. 
--------------------------- Message Trailer ------------------------    
...text...
...text...      
---------------------  Instance Type and Transmission --------------
...text.. 
...text.. 

按行划分内容------------- Instance Type and Transmission --------------并在较新的文件中输出文本。

像这样:

文件1:

---------------------  Instance Type and Transmission --------------    
    ...text..     
    ...text.. 
    --------------------------- Message Trailer ------------------------    
    ...text...
    ...text...  

文件2:

---------------------  Instance Type and Transmission --------------
...text.. 
...text.. 

Perl 和 awk 做到这一点非常简单,我找到了一些示例,在 powershell 中没有任何内容,只有按大小拆分的文本文件。

感谢@CB。我以对多个文件有效的解决方案结束:

  $InPC = "C:\Scripts"
Get-ChildItem -Path $InPC -Filter *.txt | ForEach-Object -Process { 
        $basename= $_.BaseName   
        $m = ( ( Get-Content $_.FullName | Where { $_ | Select-String "---------------------  Instance Type and Transmission --------------" -Quiet } | Measure-Object | ForEach-Object { $_.Count } ) -ge 2) 
        $a = 1
        if ($m) {
  Get-Content $_.FullName | % {

    If ($_ -match "---------------------  Instance Type and Transmission --------------") {
        $OutputFile = "$InPC\$basename _$a.txt"
        $a++
    }    
    Add-Content $OutputFile $_
    }
  Remove-Item $_.FullName 
  }
  }
4

1 回答 1

2

像这样的东西应该工作:

$InputFile = "c:\path\myfiletosplit.txt"
$Reader = New-Object System.IO.StreamReader($InputFile)
$a = 1
While (($Line = $Reader.ReadLine()) -ne $null) {
    If ($Line -match "---------------------  Instance Type and Transmission --------------") {
        $OutputFile = "MySplittedFileNumber$a.txt"
        $a++
    }    
    Add-Content $OutputFile $Line
}

或没有 .net 类:

$a = 1
gc "c:\path\myfiletosplit.txt" | % {    
    If ($_ -match "---------------------  Instance Type and Transmission --------------") {
        $OutputFile = "MySplittedFileNumber$a.txt"
        $a++
    }    
    Add-Content $OutputFile $_
}
于 2014-06-16T08:00:57.367 回答