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

grep 'string1\|string2' filename

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


当前回答

对于多行匹配:

echo -e "test1\ntest2\ntest3" |tr -d '\n' |grep "test1.*test3"

or

echo -e "test1\ntest5\ntest3" >tst.txt
cat tst.txt |tr -d '\n' |grep "test1.*test3\|test3.*test1"

我们只需要删除换行符,它就工作了!

其他回答

你应该有这样的grep:

$ grep 'string1' file | grep 'string2'

你可以尝试这样做:

(pattern1.*pattern2|pattern2.*pattern1)

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

git grep 'string1.*string2.*string3'

你可以使用

grep 'string1' filename | grep 'string2'

Or

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

如果您有一个grep,其中有一个-P选项用于有限的perl regex,您可以使用

grep -P '(?=.*string1)(?=.*string2)'

它的优点是处理重叠的字符串。使用perl作为grep更直接,因为你可以更直接地指定and逻辑:

perl -ne 'print if /string1/ && /string2/'