【问题标题】:Check if a condition is met by a line within a TXT but "in an advanced way"检查 TXT 中的一行是否满足条件但“以高级方式”
【发布时间】:2023-02-09 19:10:15
【问题描述】:

我有一个 1300 兆字节的 TXT 文件(很大)。我想构建做两件事的代码:

  1. 每一行的开头都包含一个唯一的 ID。如果满足该“组”ID 的条件,我想检查所有具有相同唯一 ID 的行。 (这回答了我:满足所有条件的唯一 ID X 有多少行)
  2. 如果脚本完成,我想从 TXT 中删除满足条件的所有行(参见 2)。因此,我可以重新运行脚本并设置另一个条件来“缩小”整个文档的范围。

    经过几个循环后,我终于有了一组适用于文档中所有行的条件。 看来我目前的做法很慢。(一个周期需要几个小时)。我的最终结果是一组适用于所有代码行的条件。 如果您找到更简单的方法,请随时推荐。 欢迎帮助:)

    到目前为止的代码(没有填满 1 和 2 中的所有内容)

    foreach ($item in $liste)
    {
        
        # Check Conditions
        if ( ($item -like "*XXX*") -and ($item -like "*YYY*") -and ($item -notlike "*ZZZ*")) { 
            
         # Add a line to a document to see which lines match condition                    
            Add-Content "C:\Desktop\it_seems_to_match.txt" "$item"
            
        # Retrieve the unique ID from the line and feed array.                
            $array += $item.Split("/")[1]
    
        # Remove the line from final document
            $liste = $liste -replace $item, ""         
               
        
        }
    
                                  
    } 
    # Pipe the "new cleaned" list somewhere
        $liste | Set-Content -Path "C:\NewListToWorkWith.txt"
    # Show me the counts
        $array | group | % { $h = @{} } { $h[$_.Name] = $_.Count } { $h } | Out-File "C:\Desktop\count.txt"
    

    演示线路:

    images/STRINGA/2XXXXXXXX_rTTTTw_GGGG1_Top_MMM1_YY02_ZZZ30_AAAA5.jpg images/STRINGA/3XXXXXXXX_rTTTTw_GGGG1_Top_MMM1_YY02_ZZZ30_AAAA5.jpg images/STRINGB/4XXXXXXXX_rTTTTw_GGGG1_Top_MMM1_YY02_ZZZ30_AAAA5.jpg images/STRINGB/5XXXXXXXX_rTTTTw_GGGG1_Top_MMM1_YY02_ZZZ30_AAAA5.jpg images/STRINGC/5XXXXXXXX_rTTTTw_GGGG1_Top_MMM1_YY02_ZZZ30_AAAA5.jpg

【问题讨论】:

  • 如果您在$liste 中处理非常大量的项目,那么$array += $item.Split("/")[1] 将会以指数方式变慢,因为它附加了复制整个数组并将新项目放在副本的末尾,随着 $array 变得越来越大,需要的时间越来越长。由于您仅使用 $array 来汇总计数,请考虑改为跟踪 foreach 循环内的计数 - 例如在 foreach 上面放 $counts = @{} 然后代替 $array = ...$name = $item.Split("/")[1]; $counts[$name] += 1...

标签: powershell performance


【解决方案1】:
$Name = $item.Split("/")[1]
if (!$HashTable.Contains($Name)) { $HashTable[$Name] = [Collections.Generic.List[String]]::new() }
$HashTable[$Name].Add($Item)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2014-04-08
    • 2021-03-22
    • 2018-10-10
    相关资源
    最近更新 更多