【发布时间】:2021-10-29 02:18:23
【问题描述】:
我有一个应该被 grep 过滤/不匹配的列表。假设我们有一个字符串:
This is a keyword string, that should not match
所以在这种情况下应该过滤行,因为包含keyword。
This is another keyword string, that should match because important is now inside.
在这种情况下,因为单词important 包含在字符串中,它应该匹配而不是被过滤。还有一堆字,不只是important,还有expensive、attention之类的字。
keyword 在字符串中总是在important 之前。
为了简单起见,我试过了:
echo "This is a keyword string, that should not match" | grep -i --invert 'keyword'
到目前为止,这有效,输出为空。
然后用消极的眼神玩弄,我试过了
echo "This is a keyword string, that should not match" | grep -i --invert 'keyword.*?(?!important)'
但这匹配。只要引入.*?,就会匹配:
echo "This is a keyword string, that should not match" | grep -i --invert 'keyword.*?'
This is a keyword string, that should not match
希望这只能通过 grep 实现。否则一些 bash 代码行也是可以接受的。
更新 unsing -P 选项:
echo "This is a keyword string, that should not match, but now important is included" | grep -i --invert -P 'keyword.*?(?!important).*?' 返回一个空字符串
【问题讨论】:
-
如果输入是
This is a keyword string but it is inexpensive那么是否应该过滤掉? -
@Hannes :简单的正则表达式不支持后视。你可以试试
-P来玩这些功能。 -
当您说“已过滤”时,您是指“已打印”还是“已删除”?这些“一堆词”总是在每一行的“关键字”之后出现还是可以在它之前出现?请edit您的问题只是显示一个包含您的要求的 4 或 5 行输入块以及给定该输入的相关输出,以帮助阐明您要做什么。