将文本文件按Powershell中的内容分成多个文件 [英] Text file splitting in multiple files by content in Powershell

查看:142
本文介绍了将文本文件按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.. 

通过行------------- Instance Type and Transmission --------------分隔内容,并在较新的文件之间输出文本.

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

赞:

文件1:

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

文件2:

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

Perl和awk做到了这一点很简单,我发现了一些示例,在powershell中什么也没有,只有按大小分割的文本文件.

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

感谢@CB.我以适用于多个文件的此解决方案结束了:

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

推荐答案

类似的方法应该起作用:

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
}

或淘汰.net类:

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

这篇关于将文本文件按Powershell中的内容分成多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆