-拆分功能在大文件中不起作用 Powershell



我试图使用Powershell解析csv文件,但split函数不起作用。我正在比较使用拆分和原始行的文件输出。拆分仅适用于前几行。我不知道我是不是错过了什么。这是我的代码

$table = Get-Content .random.csv -ReadCount 1000
$fname_mid = 'ps.mid'
$fname_mif = 'ps.mif'
New-Item -Path . -Name $fname_mid -ItemType 'file' -Force
New-Item -Path . -Name $fname_mif -ItemType 'file' -Force
ForEach($_ In $table) 
{
$read_field = $_ -split ','
$read_line = '----' + $read_field[0] + ',-' + $read_field[9] + '-'
$read_line | Out-File -Encoding 'UTF8' -FilePath $fname_mid -Append
$_ | Out-File -Encoding 'UTF8' -FilePath $fname_mif -Append
}

用于测试的文件https://www.dropbox.com/s/99zgerh2akemgy3/random.csv?dl=0

你的问题中的问题(也由评论列出(在账户中:

  • 来自@Lee_Dailey:
    this>>>ForEach($_ In $table)<lt<实际上otta触发了一个错误。$_变量是当前管道项目。。。而且你没有使用管道。将其替换为适当的当前项变量[也许是$T_Item],然后看看会发生什么
  • From@JosefZ:
    -ReadCount指定一次通过管道发送多少行内容。因此,
    $Table.Count=>40和$Table[0].Gettype()=>Object[]
    ($Table[0] -split [System.Environment]::NewLine).Count=>1000和
    ($Table[-1] -split [System.Environment]::NewLine).Count=>233
  • 在所提供的示例中,您有9列,这意味着最后一项是
    $read_field[8]CD_10不是9(
  • 这句话,$_ | Out-File -Encoding 'UTF8' -FilePath $fname_mif -Append没有多大作用(除非你的源代码不是UTF8,但还有其他方法可以做到这一点(
  • 您希望如何处理输入文件中的引号

你会得到这样的东西:

$table = Get-Content .random.csv
$fname_mid = 'ps.mid'
$fname_mif = 'ps.mif'
New-Item -Path . -Name $fname_mid -ItemType 'file' -Force
New-Item -Path . -Name $fname_mif -ItemType 'file' -Force
ForEach($Line In $table) 
{
$read_field = $Line -split ','
$read_line = '----' + $read_field[0] + ',-' + $read_field[8] + '-'
$read_line | Out-File -Encoding 'UTF8' -FilePath $fname_mid -Append
# $Line | Out-File -Encoding 'UTF8' -FilePath $fname_mif -Append
}

但是,您低估了Import-csv的性能(以及易用性((正如@Walter Mitty所评论的(和它附带的复杂PowerShell管道。关键是,如果您想将其与为流式传输构建的cmdlet进行比较,则不能仅基于单个命令来衡量的性能。在这种情况下,您需要测量完整的解决方案

如果您的(更正后的(示例花费的时间超过7分钟,则
流式传输将花费不到3秒

Import-Csv .random.csv -Head (0..8) | 
ForEach-Object {"----$($_.0),-$($_.8)-"} | 
Set-Content .fname_mid

最新更新