您可以使用or多个字符串:
grep -v "string1\|string2\|string3" filename
Run Code Online (Sandbox Code Playgroud)
这将排除包含string1, string2, 的行string3。
在基本正则表达式(以上版本)中,正则表达式元字符失去了其特殊意义,需要进行转义。
使用扩展正则表达式,您无需转义|:
grep -Ev "string1|string2|string3" filename
Run Code Online (Sandbox Code Playgroud)
如果列表包含在文件中,请使用-f选项:
grep -v -f list_to_exclude filename
Run Code Online (Sandbox Code Playgroud)
如评论中所述,如果模式是一组字符串,您可以提供-F选项以加快速度grep:
grep -F -v -f list_to_exclude filename
Run Code Online (Sandbox Code Playgroud)
从手册:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by
newlines, any of which is to be matched. (-F is specified by
POSIX.)
Run Code Online (Sandbox Code Playgroud)
下面的例子应该进一步解释它。给定一个输入文件,说input.txt:
This is line.
This is line2.
This is line3.
This is line4.
This is line*.
Run Code Online (Sandbox Code Playgroud)
现在使用命令:
grep -v 'line*' input.txt
Run Code Online (Sandbox Code Playgroud)
不会产生任何结果,因为该模式 line*被解释为正则表达式,并且会匹配给定输入文件中的所有行并-v反转匹配。如果line*是固定字符串而不是正则表达式,则提供-F选项,即说:
grep -F -v 'line*' input.txt
Run Code Online (Sandbox Code Playgroud)
会产生:
This is line.
This is line2.
This is line3.
This is line4.
Run Code Online (Sandbox Code Playgroud)
此外,由于grep现在不是在寻找模式,而是在寻找固定字符串,因此比不使用该-F选项要快得多。