如何在 Linux 上反轉 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()" *
在上面的命令中,我們使用了 **-s** 標誌,這將幫助我們避免在執行命令的目錄中存在的每個子目錄都收到警告。
輸出
main.go:120:func main() {}
反轉 Grep 表示式
為了反轉 grep 表示式,我們只需要在 grep 命令中使用 **-v** 標誌。
考慮下面顯示的命令,該命令將列印所有以 **.go** 副檔名結尾的檔案。
命令
ls -R |grep -E *\go
輸出
immukul@192 src % ls -R |grep -E *\go grep: learning-go: Is a directory grep: livego: Is a directory grep: todd-go: Is a directory
命令
現在要反轉 grep 命令,請在您的終端中鍵入以下命令。
ls -R |grep -v -E *\go
輸出
grep: learning-go: Is a directory grep: livego: Is a directory main.go:package main main.go: main.go:import ( main.go: "bytes" main.go: "fmt" main.go: . .
廣告