grep是 Linux下用來在檔案中尋找文字的工具。
語法
grep [options] [pattern] [files]
常用 Option
| grep command options | |
| Matching Control | |
| -e PATTERNS | 指定搜尋的 pattern,可以宣告多次。 |
| -i, --ignore-case | 忽略大小寫。 |
| -v, --invert-match | 印出不符合的結果。 |
| -w | whole 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字串的檔案名稱。