正则表达式查找包含 foo_bar 或不包含 foo 的所有行

标签 regex grep

我很难编写一个正则表达式放入 grep 中以匹配包含 foo_bar 的所有行以及不包含 foo_.* 的所有其他行(除了 foo_bar 应该仍然匹配)。

因此:

foo_bar Line 1
foo_baz Line 2
Line 3
foo_biz Line 4

我希望返回第 1 行和第 3 行。

注意,我不能只匹配 not foo_baz 和 not foo_biz,因为 baz 和 biz 可以有很多很多东西。它需要是 foo_.*

最佳答案

在 OS X 下,我对您的输入执行了以下命令:

$ grep -P -v '^foo_(?!bar)' test.txt 
foo_bar Line 1
Line 3

请注意:

-P, --perl-regexp
       Interpret PATTERN as a Perl regular expression.
-v, --invert-match
       Invert the sense of matching, to select non-matching lines.

关于正则表达式查找包含 foo_bar 或不包含 foo 的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12497527/

相关文章:

bash - grep 获取 csv 文件的值

json - Linux grep命令从json中查找key的值

c# - 正则表达式 - 匹配不匹配字母字符子集的字母字符 (C#)

r - 如何在不使所有列都变为字符的情况下在整个数据帧上应用正则表达式

bash - 使用 GREP 对数据进行子集化

regex - 如何计算只有换行符的行?

linux - 使用 grep 和 cut 过滤文本文件以仅显示以  ‘m’  ‘w’ 或  ‘s’ 开头的用户名及其主目录

java - 正则表达式 : How to avoid matching a word in a string upon a condition

python - 如何使用正则表达式用空格替换字符之间的破折号

c# - 快速文本预处理