2013-07-28 30 views

回答

4

您可以使用此命令。希望這能幫助你。

grep -o yourWord file | wc -l 
+0

如果一行包含兩次該詞怎麼辦? – delnan

+1

我的例子已經計算在內。你可以嘗試一下,如果你想。 –

0

使用grep -c選項來計算搜索模式的出現次數。

grep -c searchString file 
+2

這是錯誤的。 'grep -c'不計數,但用於匹配行,而不是出現次數。 – Kent

0

awk的解決方案:

awk '{s+=gsub(/word/,"&")}END{print s}' file 

測試:

kent$ cat f 
word word word 
word 
word word word 

kent$ awk '{s+=gsub(/word/,"&")}END{print s}' f 
7 

,如果你想匹配一個確切的詞可能需要添加單詞邊界。

0

是的,我知道你想要一個grep的解決方案,但我最喜歡的Perl與勞力士運營商不能在這裏失蹤...;)

perl -0777 -nlE 'say $n=()=m/\bYourWord\b/g' filename 
#        ^^^^^^^^ 

如果想要同比匹配YourWord與另一封狀包圍abcYourWordXYZ,使用

perl -0777 -nlE 'say $n=()=m/YourWord/g' filename 
相關問題