2012-06-04 41 views
4

我試圖計算包含一組字符串中的所有字符串的文件夾中的所有文本文件,即基本上是AND運算符。每個文件中字符串的順序可能會有所變化,最好是我正在尋找一個單行程。計算包含所有匹配字符串的文件,即AND運算符?

I.e.我試圖完成這樣的:

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

但是,上述說法計算含有兩種「STR1」或「STR2賽車」,但所有的文件我試圖做一個與運算,而不是一個區別或者,因此只計算包含「str1」和「str2」的文件。

問候,奧拉

+1

我也使用多選字符串在http發現在解決這個問題。 com/questions/3920383/how-to-use-powershell-select-string-to-find-more-one-pattern-in-a-file –

回答

3

這或許可以用-AND運營商做的工作:

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

這似乎是爲了完成這項工作,謝謝。 –

1

據我所知,這不可能做到嬌滴滴。因此,也許像這樣(未經):

@(Get-ChildItem | 
    Where-Object { 
     $failed = $false 
     $file = Get-Content $_ 
     $strings | ForEach-Object { 
     if (!($file -match $_)) { $failed = $true } 
     } 
     !$failed 
    }).Count 
0
@(Get-ChildItem C:\temp -Filter "file*" | 
    where { ($_ | Select-String str1 -Quiet) -and ($_ | Select-String str2 -Quiet)} 
).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

+0

這項工作將如何進行?下游的選擇字符串在前面的選擇字符串上,而不是在文件上。 – manojlds

+0

啊,你說得對。它需要一些幫助來獲得中間的「get-childitem」調用。對於那個很抱歉。我已經更新了我的答案。 –

+0

隨着更正,這也很好,所以我希望我可以接受這兩個答案。 –