常用的有如下兩種方式:
1.VIM
用vim打開文件,然后輸入:
:%s/hello//gn
如下圖:
圖中的例子就是統計文本中”hello”字符串出現的次數
說明:
%s/pattern/string/flags 意思是把pattern替換為string
參數說明:
% - 指明操作區間,%表示全文本;可以使用1,$或者行區間代替 %s相當於1,$s
s – substitute,表示替換
g是全局
pattern - 要查找的字符串
// - 替代文本應該放在這里,兩個斜杠中間沒有任何字符表示無替代文本
g – Replace all occurences in the line. Without this argument, replacement occurs only for the first occurence in each line.
n – Report the number of matches, and do not actually substitute. 這是核心功能,同時也說明為什么//之間可以添加任意字符。
一些引申出的應用:
(1) :k,ls/pattern//gn
統計k行到l行出現pattern的次數
(2) :%s/pattern//gn
統計在當前編輯文本出現的次數
2.GREP配合wc命令 統計在文件中出現的行數
grep -o "hello" demo.log | wc -l
如下圖:
另外附上幾個grep常用的參數:
-c 只顯示有多少行匹配 ,而不具體顯示匹配的行
-i 在字符串比較的時候忽略大小寫
-n 在每一行前面打印該行在文件中的行數