如何在Linux中使用grep進行多行搜尋?
為了能夠grep檔案中存在的多個行的模式,我們將使用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
現在,讓我們考慮一個案例,我們想要在特定目錄(例如dir1)中的所有檔案中查詢特定模式。
語法
grep -rni "word" *
在上面的命令中,用以下內容替換“word”佔位符:
為此,我們使用如下所示的命令:
命令
grep -rni "func main()" *
上述命令將嘗試在特定目錄以及子目錄中的所有檔案中查詢字串“func main()”。
輸出
main.go:120:func main() {}
如果我們只想在一個目錄中查詢特定模式,而不是在子目錄中查詢,則需要使用以下命令:
grep -s "func main()" *
現在假設我們有一個名為sample.txt的文字檔案,其內容如下所示。
$ immukul@192 linux-questions-code % cat sample.txt blabla blabla foofoo here is the text2strike Just a pattern bar blabla blabla
現在搜尋多行模式的命令如下所示
grep -Pzo "(?s)^(\s*)\N*/foo/,/bar/p.*?{.*?^\1}" .txt輸出
foofoo here is the text2strike just a pattern bar
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP