天天看點

find 排除_Linux/unix下 grep如何排除目錄檔案關鍵字Grep排除關鍵字Grep排除目錄Grep排除檔案Grep排除二進制檔案

在linux/unix中,使用 grep 排除功能,能夠幫助我們更精确地搜尋到所需求的内容。

grep指令支援多種排除方法,包括grep排除目錄,grep排除檔案,grep排除二進制檔案以及grep排除關鍵字。

今天,我們将重點介紹上述幾個grep 排除示例。

Grep排除關鍵字

Grep排除關鍵字或單詞,是我們在使用linux grep指令中最常用的功能。

grep指令排除關鍵字,我們可以使用grep -v選項,該選項可以反轉比對。

  • grep -v, –invert-match

    所選行是與任何指定模式都不比對的行

grep -v 文法

# grep 排除單個關鍵字➜  grep -v "keyword" file# grep 排除多個關鍵字➜  grep -v "keyword1" file | grep -v "keyword2" | ...
           

grep -v 示例

在以下示例中,我們将使用grep搜尋關鍵字并排除特定的關鍵字。

➜  ~ grep -i 'use' test.log | grep -v "option"
           
find 排除_Linux/unix下 grep如何排除目錄檔案關鍵字Grep排除關鍵字Grep排除目錄Grep排除檔案Grep排除二進制檔案

在下面的示例中,我們将使用grep和linux 管道來排除多個關鍵字。

➜  ~ grep -i 'use' test.log | grep -v "option" | grep -v "find"
           
find 排除_Linux/unix下 grep如何排除目錄檔案關鍵字Grep排除關鍵字Grep排除目錄Grep排除檔案Grep排除二進制檔案

Grep排除目錄

Grep排除目錄,我們可以使用grep –exclude-dir選項,該選項需要與grep -R選項一起使用。

  • grep –exclude-dir

    如果指定-R,則從搜尋中排除與給定檔案名模式比對的目錄。

  • -R, -r, –recursive

    遞歸搜尋列出的子目錄。

grep --exclude-dir 文法

# grep 排除單個目錄➜  grep --exclude-dir "directory" -R "keyword" .# grep 排除多個目錄➜  grep --exclude-dir "directory1" --exclude-dir "directory2" -R "keyword" .
           

grep --exclude-dir 示例

➜  grep --exclude-dir "test" -R "grep" ....➜  grep --exclude-dir "test" --exclude-dir "backup" -R "grep" ....
           
find 排除_Linux/unix下 grep如何排除目錄檔案關鍵字Grep排除關鍵字Grep排除目錄Grep排除檔案Grep排除二進制檔案

Grep排除檔案

Grep排除檔案,與排除目錄一樣,我們可以使用grep –exclude選項,該選項将從搜尋中排除與給定檔案名模式比對的檔案。

grep --exclude 文法

# grep exclude a file➜  grep --exclude "file" "keyword" files# grep exclude multiple files➜  grep --exclude "file1" --exclude "file1" "keyword" files
           

grep --exclude 示例

➜ grep --exclude "test.log" "grep" *.log...➜ grep --exclude "test.log" --exclude "m.log" "grep" *.log...
           
find 排除_Linux/unix下 grep如何排除目錄檔案關鍵字Grep排除關鍵字Grep排除目錄Grep排除檔案Grep排除二進制檔案

Grep排除二進制檔案

當使用grep指令模式搜尋時,我們經常會找到一些二進制檔案,這些不是我們所需要的,是以我們需要排除這些二進制檔案。

Grep排除二進制檔案,我們可以使用grep -I 選項,它可以在搜尋時忽略二進制檔案。

grep -I 文法

➜ grep -I "keyword" .
           

grep -I 示例

➜ grep -RI "grep" .
           
find 排除_Linux/unix下 grep如何排除目錄檔案關鍵字Grep排除關鍵字Grep排除目錄Grep排除檔案Grep排除二進制檔案