【问题标题】:PowerShell - Distinct values in column of multiple filesPowerShell - 多个文件的列中的不同值
【发布时间】:2016-11-15 16:48:29
【问题描述】:

我正在尝试读取一组| 管道分隔的文本文件,并获取每个文件的特定列中唯一值的数量,以及文件中的行数。我尝试使用Import-CSV,但这需要花费数小时并占用大量内存。文件范围从 20MB 到 500MB,10-15 个文件。

使用流式阅读器会更快吗?我将如何计算唯一值?

Get-ChildItem .\*filtered.txt -Name  | 
ForEach-Object {
    if($dayofweek -eq 1) {
        $importFile = Import-Csv $_ -Delimiter '|'
    } else {
        $importFile = Import-Csv $_ -Delimiter '|' -Header @("a", "Order-ID", "c", "d", "e", "f", "g", "h")
    }
    $numRows = $importFile | Measure-Object | Select-Object -expand count
    $numUniqueOrderID = $importFile | Select Order-ID -Unique
    echo "Filename: $_ `t Rows: $numRows `t"
    echo "Unique Order-IDs"
    $numUniqueOrderID
    echo `n
}

【问题讨论】:

    标签: powershell count unique streamreader import-csv


    【解决方案1】:

    Streamreader 的速度会快无数倍。所以想法是使用 Streamreader 将数据放入内存,然后执行$data = ConvertFrom-Csv -InputObject $result。之后,您可以执行Sort-Object -unique 之类的操作或添加-Property 进行排序。

    编辑:或者,如果你不想弄乱 Streamreader,你可以使用$content = Get-Content $file -ReadCount 0,是的,你会损失大约 0.01% 的效率,但为什么要麻烦。

    【讨论】:

      【解决方案2】:

      不确定

      Get-ChildItem .\*filtered.txt -File   | 
      % {
          if($dayofweek -eq 1) 
           {$numUniqueOrderID = (Import-Csv $_.FullName -Delimiter '|' | Select Order-ID -Unique).Count} 
          else 
           {$numUniqueOrderID = (Import-Csv $_.FullName -Delimiter '|' -Header "a", "Order-ID", "c", "d", "e", "f", "g", "h" | Select Order-ID -Unique).Count}
      
          $numRows = (gc $_.FullName  -ReadCount 0).Count
          write-host ("Filename: {0}`t Rows : {1}`nUnique Order-IDs : {2}`n" -f $_, $numRows, $numUniqueOrderID)   
        }
      

      【讨论】:

        猜你喜欢
        • 2022-10-23
        • 2019-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-30
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多