【问题标题】:Counting files containing all of the matching strings, i.e. AND operator?计数包含所有匹配字符串的文件,即 AND 运算符?
【发布时间】:2012-06-06 23:05:46
【问题描述】:

我正在尝试计算一个文件夹中的所有文本文件,该文件夹包含一组字符串中的所有字符串,即基本上是一个 AND 运算符。每个文件中字符串的顺序可能是这样,最好我正在寻找一个单行。

即我正在尝试完成类似的事情:

(Get-ChildItem -filter "file*" C:\temp |
Select-String -Pattern @(“str1", "str2")).Count

但不同的是,上面的语句计算了所有包含“str1”或“str2”的文件,但我正在尝试执行 AND 操作而不是 OR,因此只计算同时包含“str1”和“str2”。

问候,奥拉

【问题讨论】:

标签: powershell


【解决方案1】:

这也许可以用-AND 操作符完成这项工作:

(Get-ChildItem . -include *.txt -recurse |
    % {(Select-String $_ -Pattern "str1") -AND (select-string $_ -pattern "str2")} |
        where {$_ -eq $true}).count

【讨论】:

    【解决方案2】:

    如果输入字符串的数量是固定的,那么利用管道可以非常巧妙地完成:

    get-childitem c:\temp\file* |
        select-string -l str1   |
        get-childitem           |
        select-string -l str2   |
        measure-object
    

    如果您只想获取计数,而不是 Measure-Object 返回的统计信息,请将 | select -exp Count 添加到管道的末尾。

    我发现将以下内容添加到我的$profile 以进一步减少此类事情很有用。

    Set-Alias ss Select-String
    ${function:...} = { process { $_.($args[0]) } }
    

    然后,解决方案(假设默认别名)变为:

    gci c:\temp\file* | ss -l str1 | gci | ss -l str2 | measure | ... Count
    

    参考:Power and Pith - Windows PowerShell Blog

    【讨论】:

    • 这将如何工作?下游选择字符串在前面的而不是在文件上。
    • 啊,你是对的。中间的get-childitem 调用需要一点帮助。对于那个很抱歉。我已经更新了我的答案。
    • 通过更正,这也很好,所以我希望我能接受这两个作为答案。
    • @OlaTheander 谢谢!恐怕不可能同时接受这两个答案,但我很欣赏这种情绪。
    【解决方案3】:

    据我所知,这不能很好地完成。所以也许是这样的(未经测试):

    @(Get-ChildItem |
        Where-Object {
          $failed = $false
          $file = Get-Content $_
          $strings | ForEach-Object {
            if (!($file -match $_)) { $failed = $true }
          }
          !$failed
        }).Count
    

    【讨论】:

      【解决方案4】:
      @(Get-ChildItem C:\temp -Filter "file*" | 
        where { ($_ | Select-String str1 -Quiet) -and ($_ | Select-String str2 -Quiet)}
      ).Count
      

      【讨论】:

        猜你喜欢
        • 2017-11-22
        • 2019-04-24
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        • 2014-04-20
        • 2021-10-07
        • 2020-12-13
        相关资源
        最近更新 更多