grep -r “{關鍵字}” {路徑}
例如:
grep -r “test” /data/reports
grep -R --include="*.cpp" key dir
上述指令的含義:
在dir目錄下遞歸查找所有.cpp檔案中的關鍵字key
在application目錄下遞歸查找所有.sh檔案中的關鍵字 81,顯示所屬行并将查找到的結果覆寫寫入/root/t.txt中
grep -R -n --include="*.sh" 81 ./application >/root/t.txt
grep -i pattern files :不區分大小寫地搜尋。預設情況區分大小寫,
grep -l pattern files :隻列出比對的檔案名,
grep -L pattern files :列出不比對的檔案名,
grep -w pattern files :隻比對整個單詞,而不是字元串的一部分(如比對‘magic’,而不是‘magical’),
grep -C number pattern files :比對的上下文分别顯示[number]行,
grep pattern1 | pattern2 files :顯示比對 pattern1 或 pattern2 的行,
grep pattern1 files | grep pattern2 :顯示既比對 pattern1 又比對 pattern2 的行。
/< 和 /> 分别标注單詞的開始與結尾。
例如:
grep man * 會比對 ‘Batman’、‘manic’、‘man’等,
grep ‘/<man’ * 比對‘manic’和‘man’,但不是‘Batman’,
grep ‘/’ 隻比對‘man’,而不是‘Batman’或‘manic’等其他的字元串。
‘^’:指比對的字元串在行首,
‘$’:指比對的字元串在行尾,
明确要求搜尋子目錄:grep -r
或忽略子目錄:grep -d skip
當然,如果預料到有許多輸出,您可以通過 管道 将其轉到‘less’上閱讀:
$ grep magic /usr/src/linux/Documentation/* | less
完全比對一個詞
grep -R -w ‘boot’ /etc
關鍵字位于被查找檔案的哪一行
grep -R -w -n ‘boot’ /etc
關鍵字包含在那個檔案中
grep -R -w -l ‘boot’ /etc
搜尋結果寫入檔案
grep -R -w -l ‘boot’ /etc > ./output.txt
#######查詢包含某關鍵字的行數########
日志中,包含某條件的行數
find access_log.20160423.txt | xargs cat | grep .helloworld.|wc -l
例子說明:統計含"helloworld"字元串的總行數
日志中,不包含某條件的行數
find access_log.20160423.txt | xargs cat | grep -v .helloworld.|wc -l
例子說明:統計不含"helloworld"字元串的總行數