Text file splitting in multiple files by content i

2020-02-15 02:53发布

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条回答
爷的心禁止访问
2楼-- · 2020-02-15 03:12

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 $_
}
查看更多
登录 后发表回答