關鍵命令:
:%s/pattern//gn
參數說明:
% - 指明操作區間,%表示全文本;可以使用1,$或者行區間代替
s – substitute,表示替換
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
統計在當前編輯文本出現的次數
(3) cat file|greg –i pattern |wc –l
統計在文件中出現的行數