You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell统计每个日志文件中dog和cat的出现次数?

需求说明

在路径C:\Users\krivosik\Desktop\Scripts\logs下有log1.txt至log8.txt共8个日志文件,已统计出所有文件中dog和cat的总出现次数(如总共有300次dog、250次cat),现需统计每个单独文件中dog和cat各自的出现次数(例如log1.txt含30次dog、20次cat)。

你尝试过的命令:

Get-ChildItem -Recurse | Select-String "dog" -List | Select Path
解决方案

基础实现命令

以下命令可直接统计每个txt文件中两个关键词的出现次数,并输出结构化结果:

Get-ChildItem "C:\Users\krivosik\Desktop\Scripts\logs" -Filter *.txt | ForEach-Object {
    # 统计当前文件中dog的出现次数
    $dogCount = (Select-String -Path $_.FullName -Pattern "dog" -AllMatches).Matches.Count
    # 统计当前文件中cat的出现次数
    $catCount = (Select-String -Path $_.FullName -Pattern "cat" -AllMatches).Matches.Count
    # 输出包含文件名和次数的自定义对象
    [PSCustomObject]@{
        文件名       = $_.Name
        dog出现次数 = $dogCount
        cat出现次数 = $catCount
    }
}

高效优化版本(适合大文件)

如果日志文件体积较大,可通过一次性读取文件内容减少IO操作,提升效率:

Get-ChildItem "C:\Users\krivosik\Desktop\Scripts\logs" -Filter *.txt | ForEach-Object {
    # 一次性读取整个文件内容
    $fileContent = Get-Content $_.FullName -Raw
    # 基于读取的内容统计关键词次数
    $dogCount = ($fileContent | Select-String "dog" -AllMatches).Matches.Count
    $catCount = ($fileContent | Select-String "cat" -AllMatches).Matches.Count
    # 输出结果
    [PSCustomObject]@{
        文件名       = $_.Name
        dog出现次数 = $dogCount
        cat出现次数 = $catCount
    }
}

关键参数说明

  • -Filter *.txt:仅处理目标目录下的txt文件,避免无关文件干扰
  • -AllMatches:Select-String默认只返回每行第一个匹配项,加上此参数可获取所有匹配结果,从而统计总次数
  • [PSCustomObject]:将结果整理为表格形式,便于查看和后续处理

内容的提问来源于stack exchange,提问作者Gaara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:35:27