如何在 Linux 中限制 grep 返回的結果數量?


為了能夠限制 grep 命令在 Linux 中返回的結果數量,我們首先需要了解 **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

語法

grep -rni "word" *

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

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

grep -rni "func main()" *

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

輸出

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

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

grep -s "func main()" *

在上述命令中,我們使用了 **-s** 標誌,這將幫助我們避免在執行命令的目錄中存在的每個子目錄都收到警告。

輸出

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

現在,假設我有一個 **.txt** 檔案,檔案內容如下所示。

命令

immukul@192 d2 % cat 2.txt
orange apple is great together
apple not great
is apple good
orange good apple not

現在我想對包含 **‘apple’** 和 **‘orange’** 兩個單詞的所有行使用 **grep** 命令。

命令

grep 'orange' 2.txt | grep 'apple'

輸出

immukul@192 d2 % grep 'orange' 2.txt | grep 'apple'
orange apple is great together
orange good apple not

現在我們可以注意到有兩個字串與我們的 grep 查詢匹配,我們可以使用以下命令來 **限制** 結果

命令

grep -m 1 'orange' 2.txt | grep 'apple

輸出

immukul@192 d2 % grep -m 1 'orange' 2.txt | grep 'apple'

orange apple is great together

更新於: 2021-07-30

883 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.