我试图使用grep来匹配包含两个不同字符串的行。我已经尝试了以下方法,但这匹配了包含不是我想要的string1或string2的行。

grep 'string1\|string2' filename

那么我如何匹配与grep只包含两个字符串的行?


当前回答

grep ‘string1\|string2’ FILENAME 

GNU grep 3.1版

其他回答

发现仅以6个空格开始并以以下内容结束的行:

 cat my_file.txt | grep
 -e '^      .*(\.c$|\.cpp$|\.h$|\.log$|\.out$)' # .c or .cpp or .h or .log or .out
 -e '^      .*[0-9]\{5,9\}$' # numers between 5 and 9 digist
 > nolog.txt

你应该有这样的grep:

$ grep 'string1' file | grep 'string2'
grep '(string1.*string2 | string2.*string1)' filename

将得到line与string1和string2在任何顺序

如果git被初始化并添加到分支,那么最好使用git grep,因为它非常快,它会在整个目录内搜索。

git grep 'string1.*string2.*string3'

你可以使用

grep 'string1' filename | grep 'string2'

Or

grep 'string1.*string2\|string2.*string1' filename