如何在 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()”。
Learn Linux/Unix in-depth with real-world projects through our Linux/Unix certification course. Enroll and become a certified expert to boost your career.
输出
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: . .
广告