如何将一行中存在的两个字符串与 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()" *
上面的命令将尝试main()在特定目录和子目录中的所有文件中查找字符串“func”。
输出结果
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
现在我想对包含grep'orange'|两个词的所有行使用grep命令。2.txtgrep'apple''apple'和'orange'。
命令
grep 'orange'2.txt| grep 'apple'输出结果
immukul@192 d2 % grep 'orange'2.txt| grep 'apple' orange apple is great together orange good apple not
热门推荐
10 小孩生日祝福语简短励志
11 默克尔离职祝福语简短
12 亲人提车祝福语简短
13 书写大赛祝福语范文简短
14 求婚蛋糕卡片祝福语简短
15 情侣520的祝福语简短
16 古风考试祝福语 唯美简短
17 高寿生日祝福语简短独特
18 中秋骚气祝福语简短情人