小编Sco*_*Chi的帖子

打印匹配模式 1 的行,除非下一行包含模式 2

我想匹配包含 foo 的行,除非下一行包含 bar。因此给定一个包含以下内容的文件:

1 foo 1 
foo 2
baz bar bap
Run Code Online (Sandbox Code Playgroud)

只会1 foo 1打印。我在https://regex101.com/r/ZMZsiN/1/foo(?!.*\n.*bar)/上使用负前瞻使其工作,但在命令行上使用 grep 和 perl 使其工作均失败。任何在 perl、sed、awk 或 python 中使用 grep 或单行语句的解决方案都很好。Chatgpt 让我失望了。

一些尝试:

$grep -Pwe 'foo(?!.*\n.*bar)' testfile
1 foo 1 
foo 2
Run Code Online (Sandbox Code Playgroud)
$perl -wnl -e  /'foo(?!\n.*bar)/ and print' testfile
1 foo 1 
foo 2
Run Code Online (Sandbox Code Playgroud)
$perl -ne 'print if /foo/ && ($_ = <>) !~ /bar/' testfile
foo 2
Run Code Online (Sandbox Code Playgroud)

最后一个是基于 chatgpt 提供的内容,并且很接近,但我的 perlfu 还不够好,无法找出问题所在。

grep perl regular-expression

3
推荐指数
1
解决办法
194
查看次数

标签 统计

grep ×1

perl ×1

regular-expression ×1