V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
1054850490
V2EX  ›  PowerShell

这个 powershell "比对”命令能优化吗?

  •  
  •   1054850490 · 2023-02-17 08:28:11 +08:00 · 1498 次点击
    这是一个创建于 426 天前的主题,其中的信息可能已经有所发展或是发生改变。
    刚开始运行效率还挺快,但是当文本量起来后就慢了,所以如何提高下面命令的效率
    ```
    *>&1 | ForEach-Object {if($_ -notin (Get-Content 888.txt)){Add-Content 888.txt $_ -Encoding utf8; $_}}

    ```

    规则是“整行”内容匹配,而不是“包含”内容匹配

    解释一下,上面是将 888.txt 里的内容跟 powershell 控制台的输出进行比对,也就是说,控制台输出了“hello world”的话,就会比对 888.txt 有没有相同的内容,如果 888.txt 里也有一整行写着“hello world”则不追加写入 txt
    4 条回复    2023-02-18 05:27:56 +08:00
    fenglala
        1
    fenglala  
       2023-02-17 08:33:46 +08:00 via Android
    mudssky
        2
    mudssky  
       2023-02-17 09:01:05 +08:00
    避免多次读取和写入同一个文件。可以将已存在的文本内容加载到变量中,并将新内容添加到变量中,然后一次性将变量写入文件。这样可以减少磁盘 I/O 操作,提高执行速度。例如:

    $content = Get-Content 888.txt -Raw
    Get-ChildItem -Path "C:\Path\To\Directory" -Recurse -ErrorAction SilentlyContinue | ForEach-Object {
    if ($_.Attributes -ne "Directory") {
    $newContent = Get-Content $_.FullName -Raw
    if ($newContent -notin $content) {
    $content += $newContent
    }
    }
    }

    Set-Content 888.txt -Value $content -Encoding utf8


    帮你查的
    darklights
        3
    darklights  
       2023-02-17 10:01:41 +08:00
    空间换时间

    $dict = @{}; gc a.txt | ?{$_ -notmatch '^\s*$'} | %{$dict[$_]=1}
    gc b.txt | ?{$_ -notmatch '^\s*$'} | ?{-not $dict[$_]} | Add-Content a.txt
    1054850490
        4
    1054850490  
    OP
       2023-02-18 05:27:56 +08:00
    @fenglala 但是这个并不是 powershell ,而是 bash
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1221 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:26 · PVG 07:26 · LAX 16:26 · JFK 19:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.