如何在Linux系統中查詢名稱包含特定字串的所有檔案?


為了在Linux命令列中查詢名稱包含特定字串的所有檔案,我們將使用**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
-R : stands for recurse, would go into subdirectories as well.

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

語法

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() {}

示例

命令

grep -R "apples" .

輸出

immukul@192 linux-dir1% grep -R "apples" .

./d1/file.txt:apples
./d1/file.txt:applesauce
./d1/file.txt:applesnits
./d1/file.txt:dapples
./d1/file.txt:grapples
./d1/file.txt:mayapples
./d1/file.txt:pineapples
./d1/file.txt:sapples
./d1/file.txt:scrapples
./d2/2.txt:orange apples is great together
./d2/2.txt:apples nto great
./d2/2.txt:is apples good

更新於:2021年7月29日

4K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

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