文本文件按Powershell中的内容拆分为多个文件

时间:2014-06-16 06:49:52

标签: powershell filesplitting

我正在阅读很多帖子 - 但对我个人来说没什么。 我需要以下面的形式拆分文本文件:

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

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

像这样:

File1中:

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

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

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