为什么这个 "grep -P" 不符合我的预期?
Why does this "grep -P" not do what I expect?
$ cat file
Here's a line.
This line has one blank line above it.
This line has two blank lines above it.
This line has three blank lines above it.
This line has four blank lines above it.
我想在文本文件中查找所有以两个或多个空行开头的行。我认为 应该 执行此操作的命令只会找到恰好有两个前空行的行:
$ grep -Pzo '(?<=\n\n\n).*' file
This line has two blank lines above it.
grep 手册页(针对 GNU grep 2.21)确实将 -P 选项标记为 "highly experimental",但声称主要问题是未实现的行为,它会就此发出警告。但是,乍一看,这似乎是错误的行为:我无法真正解释为什么 在 之前 正则表达式的后视部分会影响表达式是否匹配。我是不是忽略了一些细微之处?
我找到了其他方法来完成我想要的,所以我真的不需要任何建议。然而,这个 grep 命令是最优雅的解决方案(除了它不工作带来的轻微不便),我想了解它失败的原因,以及是否可以通过调整使其成功。谢谢
在对 PCRE 库进行一些调查和修改之后,我实际上发现这种不正确的行为是由 grep
本身引起的。
grep
2.21 似乎是第一个不能正常工作的版本,例如:
➜ ~ grep-2.21/src/grep -Pzo '(?<=\n\n\n).*' ~/file
This line has two blank lines above it.
➜ ~ grep-2.20/src/grep -Pzo '(?<=\n\n\n).*' ~/file
This line has two blank lines above it.
This line has three blank lines above it.
This line has four blank lines above it.
根据 grep
(git repository).
,自 2.20 以来引入了相当多的变化
总而言之,这是一个错误,应该报告。
$ cat file
Here's a line.
This line has one blank line above it.
This line has two blank lines above it.
This line has three blank lines above it.
This line has four blank lines above it.
我想在文本文件中查找所有以两个或多个空行开头的行。我认为 应该 执行此操作的命令只会找到恰好有两个前空行的行:
$ grep -Pzo '(?<=\n\n\n).*' file
This line has two blank lines above it.
grep 手册页(针对 GNU grep 2.21)确实将 -P 选项标记为 "highly experimental",但声称主要问题是未实现的行为,它会就此发出警告。但是,乍一看,这似乎是错误的行为:我无法真正解释为什么 在 之前 正则表达式的后视部分会影响表达式是否匹配。我是不是忽略了一些细微之处?
我找到了其他方法来完成我想要的,所以我真的不需要任何建议。然而,这个 grep 命令是最优雅的解决方案(除了它不工作带来的轻微不便),我想了解它失败的原因,以及是否可以通过调整使其成功。谢谢
在对 PCRE 库进行一些调查和修改之后,我实际上发现这种不正确的行为是由 grep
本身引起的。
grep
2.21 似乎是第一个不能正常工作的版本,例如:
➜ ~ grep-2.21/src/grep -Pzo '(?<=\n\n\n).*' ~/file
This line has two blank lines above it.
➜ ~ grep-2.20/src/grep -Pzo '(?<=\n\n\n).*' ~/file
This line has two blank lines above it.
This line has three blank lines above it.
This line has four blank lines above it.
根据 grep
(git repository).
总而言之,这是一个错误,应该报告。