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

grep 'string1\|string2' filename

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


当前回答

grep ‘string1\|string2’ FILENAME 

GNU grep 3.1版

其他回答

当两个字符串按顺序排列时,在grep命令中放入一个模式:

$ grep -E "string1(?.*)string2" file

例如,在名为Dockerfile的文件中包含以下行:

FROM python:3.8 as build-python
FROM python:3.8-slim

要获取包含字符串的行:FROM python和as build-python,然后使用:

$ grep -E "FROM python:(?.*) as build-python" Dockerfile

然后输出将只显示包含这两个字符串的行:

FROM python:3.8 as build-python

你可以尝试这样做:

(pattern1.*pattern2|pattern2.*pattern1)

假设我们需要在文件testfile中找到多个单词的计数。 有两种方法

1)使用grep命令与regex匹配模式

grep -c '\<\(DOG\|CAT\)\>' testfile

2)使用egrep命令

egrep -c 'DOG|CAT' testfile 

使用egrep,您无需担心表达式,只需通过管道分离器分离单词。

对于多行匹配:

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"

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

发现仅以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