如何在 Linux 中使用管道連線兩個 grep 命令後保留顏色?


為了在使用管道連線兩個 **grep** 命令後保留顏色,我們首先必須瞭解 **grep** 命令是什麼以及如何在 Linux 中使用它。

Linux 中的 grep 命令用於在檔案中搜索特定字元模式。它是 Linux 中最常用的實用程式命令之一,用於顯示包含我們嘗試搜尋的模式的行。

通常,我們嘗試在檔案中搜索的模式稱為正則表示式。

語法

grep [options] pattern [files]

雖然有很多不同的選項可供我們使用,但一些最常用的選項是:

-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern

現在,讓我們考慮一個案例,我們想在特定目錄(例如 dir1)中的所有檔案中查詢特定模式。

語法

grep -rni "word" *

在上面的命令中,用以下內容替換“word”佔位符:

為此,我們使用以下命令:

grep -rni "func main()" *

上面的命令將嘗試在特定目錄以及子目錄中的所有檔案中查詢字串“func main()”。

輸出

main.go:120:func main() {}

如果我們只想在一個目錄中查詢特定模式,而不是在子目錄中查詢,則需要使用以下命令:

grep -s "func main()" *

考慮以下顯示的簡單檔案的輸出,該檔案包含三個數字。

immukul@192 dir1 % cat bar
11
12
13

現在,當我們在上述檔案中使用 grep 命令 **(grep -e '1' *)** 時,輸出將不會帶顏色。

immukul@192 dir1 % grep -e '1' *
11
12
13

現在,如果我們使用帶有管道連線的兩個 grep 命令,顏色也將不會保留。

immukul@192 dir1 % grep -e '1' * | grep -ve '12'
11
13

我們可以使用以下命令來確保顏色得到保留。

命令

grep -e '1' * | grep -ve '12' | grep -e '1' --color=always

輸出

immukul@192 dir1 % grep -e '1' * | grep -ve '12' | grep -e '1' --color=always
11
13

更新於:2021年7月30日

234 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告