2024年9月24日 星期二

[Linux] grep 命令使用筆記

grep是 Linux下用來在檔案中尋找文字的工具。

語法


grep [options] [pattern] [files]

常用 Option


grep command options
Matching Control
-e PATTERNS指定搜尋的 pattern,可以宣告多次。
-i, --ignore-case忽略大小寫。
-v, --invert-match印出不符合的結果。
-wwhole word only。
General Output Control
-c, --count只印出符合結果的行數。
-l只印出符合結果的檔案名稱。
-o只印出符合的部分。
Output Line Prefix Control
-h, --no-filename只顯示符合的結果,不顯示檔案名稱。
-n, --line-number在符合的結果前面加上行號。
Context Line Control
-A NUM印出符合的結果後面 NUM行。
-B NUM印出符合的結果前面 NUM行。
-C NUM印出符合的結果前面及後面 NUM行。
File and Directory Selection
-r, --recursive尋找指定目錄下所有檔案的符合結果。

使用方法


grep "abcd" file.txt
grep -e "abcd" file.txt

在 file.txt中尋找有 abcd字串的行。


grep -e "abcd" -e "efgh" file.txt

在 file.txt中尋找有 abcd字串及有 efgh的行。


grep -e "abcd" -e "efgh" file.txt file2.txt

在 file.txt和 file2.txt中尋找有 abcd字串及有 efgh的行。


grep -r "abcd" .

在當前目錄下的所有檔案中尋找有 abcd字串的行。


grep -r -l "abcd" .

只列出當前目錄下的所有檔案中有 abcd字串的檔案名稱。


沒有留言:

張貼留言