使用grep命令時如何排除目錄?


概述

我們經常執行grep命令來查詢檔案中的特定文字字串。grep命令提供了一些附加功能,使搜尋更加高效。其中一項功能允許您排除某些目錄的遞迴搜尋。這在搜尋大量資料時非常有用。

Grep 可以與 -r 選項一起使用,該選項允許您指定多個模式,然後使用 -v 選項僅顯示與您的模式匹配的檔案。

我們將討論實現此目標的不同方法。

排除單個目錄

最簡單的方法是將排除的目錄名稱新增到檔案路徑的末尾。例如:

grep -r 'pattern' /path/to/directory1/*

這將找到指定目錄或任何子目錄中的所有檔案。但是,它不會排除任何內容。

要排除單個目錄,您需要包含 -d 標記。因此,如果您要排除 /home 目錄,可以使用:

grep -rd '/home' /path/to/*

我們將建立一些檔案和資料夾作為示例。

$ mkdir tdir1 tdir2 tdir3 logs apache-logs
$ echo "This is sample text from tdir1/file1.txt file" > tdir1/file1.txt
$ echo "This is sample text from tdir2/file2.txt file" > tdir2/file2.txt
$ echo "This is sample text from tdir3/file3.txt file" > tdir3/file3.txt
$ echo "This is sample text from logs/service.log file" > logs/service.log
$ echo "This is sample text from apache-logs/apache.log file" > apache-logs/apache.log

現在讓我們看一下我們剛剛建立的目錄樹:

$ tree -h .
.
├──   [4.0K]  tdir1
     └── [  45]  file1.txt
├──   [4.0K]  tdir2
     └── [  45]  file2.txt
├──   [4.0K]  tdir3
     └── [  45]  file3.txt
├──   [4.0K]  logs
     └── [  47]  service.log
└──   [4.0K]  apache-logs
      └── [  51]  apache.log

5個目錄,5個檔案

我們可以使用 grep 命令的 -exclude-dir 選項來排除目錄:

$ grep -R "sample" --exclude-dir=tdir1
logs/service.log:This is sample text from logs/service.log file
tdir3/file3.txt:This is sample text from tdir3/file3.txt file
tdir2/file2.txt:This is sample text from tdir2/file2.txt file
apache-logs/apache.log:This is sample text from apache-logs/apache.log file

在上面的示例中,grep 命令搜尋除 tdir1 之外的所有目錄中的模式。

排除多個目錄

如果您想排除多個目錄,可以使用管道字元 (|) 將它們組合成一個字串。您也可以使用萬用字元。例如,假設您有兩個要排除的目錄:

您可以使用 * 或 ? 字元來表示單個字元。如果您要查詢文字星號 (*),則應在其前面加上反斜槓進行轉義。

您可以指定多個 -exclude-directories 選項來排除多個目錄。

$ grep -R "sample" --exclude-dir=tdir1 --exclude-dir=tdir2 --exclude-dir=tdir3
logs/service.log:This is sample text from logs/service.log file
apache-logs/apache.log:This is sample text from apache-logs/apache.log file

在上面的示例中,grep 命令搜尋除 *tdir1*、*tdir2* 和 *tdir3* 之外的所有目錄中的模式。

您可以使用另一種語法來達到相同的結果。我們可以在花括號中提供目錄列表。

$ grep -R "sample" --exclude-dir={tdir1,tdir2,tdir3}
logs/service.log:This is sample text from logs/service.log file
apache-logs/apache.log:This is sample text from apache-logs/apache.log file

請注意,逗號前後不應有空格。

使用模式匹配排除目錄

如果我們要一次排除很多目錄,我們通常可以使用正則表示式來匹配它們。grep 命令支援使用 *萬用字元* 字元透過正則表示式匹配來排除目錄。

  • ? 用於匹配前面字元的零次或一次出現

  • * 用於匹配前面字元的零次或多次出現

  • \ 用於轉義萬用字元

讓我們使用模式 tdir? 來排除 tdir1、tdir2 和 tdir3 目錄:

$ grep -R "sample" --exclude-dir=tdir?
logs/service.log:This is sample text from logs/service.log file
apache-logs/apache.log:This is sample text from apache-logs/apache.log file

讓我們使用 logs\* 和 \*logs 模式來排除名稱以 logs 開頭或結尾的目錄:

$ grep -R "sample" --exclude-dir={logs\*,\*logs}
tdir1/file1.txt:This is sample text from tdir1/file1.txt file
tdir3/file3.txt:This is sample text from tdir3/file3.txt file
tdir2/file2.txt:This is sample text from tdir2/file2.txt file

結論

我們討論了三種在遞迴遍歷檔案系統時排除目錄的實用方法。這些命令可以在日常使用 Linux 系統時派上用場。

更新於:2022-12-26

4K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.