Text file splitting in multiple files by content in Powershell

我的梦境 提交于 2019-12-29 09:03:06

问题


i'm reading a lot of threads - but nothing for me personal. I need to split text file in the following form:

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

dividing content by lines ------------- Instance Type and Transmission -------------- and output text between in newer file.

Like this:

File1:

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

File2:

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

Perl and awk do this pretty simple and i found some examples, and nothing in powershell, only text file by size splitting.

Thanks to @CB. I ended with this solution valid for multiple files:

  $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:


Something like this should work:

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

or whitout .net class:

$a = 1
gc "c:\path\myfiletosplit.txt" | % {    
    If ($_ -match "---------------------  Instance Type and Transmission --------------") {
        $OutputFile = "MySplittedFileNumber$a.txt"
        $a++
    }    
    Add-Content $OutputFile $_
}


来源:https://stackoverflow.com/questions/24238016/text-file-splitting-in-multiple-files-by-content-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!