2014-09-25 253 views
0

我有一個腳本,用於統計文件中某個單詞的出現次數。隨着文件不斷增加的話,每次PowerShell都會計算出現的次數。不過,我想它停止一旦它確定一個特定的詞已經加入三次例如計數:停止PowerShell腳本計數達到三之後

蘋果 蘋果 蘋果 香蕉 香蕉 蘋果

我希望它停止一旦其認定蘋果3計數時間,而不是指望它爲4。這是我使用的PowerShell腳本:

[email protected]{} 
$Output=switch(gc c:\temp\LimitCount.txt){ {($ht.values|sort -Descending|select -first 1) -eq 3}{break} 
{$_ -match '^. +user:(.+)$' -and [string]::IsNullOrEmpty($ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value))}{$ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups [1].value)=0} 
{$_ -match '^. +user:(.+)$' -and $ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value) -eq 3}{continue} 
{$_ -match '^. +user:(.+)$'}{$ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value)++;([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value;continue} 
default {$_} 
} 
"Unfiltered results and count:" 
$output|group -NoElement 
$output|Where{$ht.keys -contains $_}|group -NoElement 
+0

爲那個特定的詞停下來,還是完全停下來? – TheMadTechnician 2014-09-25 22:06:10

回答

2

所以你沒有給我的評論作出迴應,但我們假設您想要的任何單一的不超過3比賽。我要做的是製作一個空的散列表,並對該文件的內容運行Switch命令並將結果捕獲到一個數組中

第一次驗證將檢查字符串是否匹配正則表達式,如果匹配的文本是已經在哈希表中。如果它匹配,並且不在散列表中,則將其添加到散列表。

第二個驗證檢查字符串是否與正則表達式匹配,並且哈希表條目是否等於3.如果是,則跳至文本文件的下一行。

第三個驗證只是檢查字符串是否與正則表達式匹配,如果它確實會將該匹配的哈希表條目遞增1,並傳遞匹配的文本。

第四個驗證是默認的,如果沒有其他驗證發生,那麼它只是沿着未改變的方向傳遞線。

然後,您可以輸出該數組,或者僅對與您的正則表達式匹配的內容進行過濾。該守則將是這個樣子:

[email protected]{} 
$Output=switch(gc c:\temp\test.txt){ 
    {$_ -match '^. +user:(.+)$' -and [string]::IsNullOrEmpty($ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value))}{$ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value)=0} 
    {$_ -match '^. +user:(.+)$' -and $ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value) -eq 3}{continue} 
    {$_ -match '^. +user:(.+)$'}{$ht.(([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value)++;([regex]"^(?:. +user:)(.+)$").matches($_).groups[1].value;continue} 
    default {$_} 
} 
"Unfiltered results and count:" 
$output|group -NoElement 
"Filtered for only matched items:" 
$output|Where{$ht.keys -contains $_}|group -NoElement 

鑑於輸入:你得到的輸出

A user:Apple 
A user:Apple 
A user:Banana 
Shiney tacos! 
A user:Orange 
A user:Banana 
A user:Apple 
A user:Orange 
A user:Orange 
A user:Apple 
A user:Apple 
A user:Apple 
A user:Apple 
A user:Apple 

Unfiltered results and count: 
Count Name      
----- ----      
    3 Apple      
    2 Banana     
    1 Shiney tacos!    
    3 Orange     
Filtered for only matched items: 
    3 Apple      
    2 Banana     
    3 Orange 

如果你想停下來,一旦你的達到3任何匹配都可以在第一次驗證之前立即添加以下行:

{($ht.values|sort -Descending|select -first 1) -eq 3}{break} 
+0

謝謝抱歉回覆晚了,這是我想停止後,它匹配超過3每個 – irenetate 2014-09-26 08:06:59

+0

如何修改代碼,所以它只能計數到3,而不是創建一個新的用戶具有相同的名稱。例如我有4個蘋果,它的計數爲3個蘋果,然後在一個新的線上計算另一個蘋果爲1個蘋果。但我只想要一個蘋果的結果,如:3個蘋果並停在那裏? – irenetate 2014-09-29 10:08:21

+0

這不會超過3,所以我不明白你的問題。 – TheMadTechnician 2014-09-29 15:11:27