Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

filesplitting - Text file splitting in multiple files by content in Powershell

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 
  }
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this should work:

$InputFile = "c:pathmyfiletosplit.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:pathmyfiletosplit.txt" | % {    
    If ($_ -match "---------------------  Instance Type and Transmission --------------") {
        $OutputFile = "MySplittedFileNumber$a.txt"
        $a++
    }    
    Add-Content $OutputFile $_
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...