egrep -o :Linux 和 MacOS 中的不同行为

egrep -o : different behaviour in Linux and MacOS

我有两个脚本,我想在 Linux 机器和 MacOS 机器上 运行。但是 egrep 命令的不同行为使这些脚本生成不同的输出。

特别是,当我在 Linux (Ubuntu) 上使用 egrep 时会发生这种情况:

$ echo ".test" | egrep "[a-zA-Z0-9]*"
.test
$ echo ".test" | egrep -o "[a-zA-Z0-9]*"
test
$

这就是我在 MacOS

上使用 egrep 时发生的情况
$ echo ".test" | egrep "[a-zA-Z0-9]*"
.test
$ echo ".test" | egrep -o "[a-zA-Z0-9]*"

$

第一个行为是我所期望的,第二个行为(空输出)是出乎意料的。也许这是在 MacOS 下使用 -o 选项实现 egrep 的错误?

或者,如果第二种行为也是正确的,您知道第二种情况获得相同行为的方法吗?

我试图查看这两个命令对应的 man 页面,这是从 Linux 手册页中提取的:

 -o, --only-matching
        Print only the matched (non-empty) parts of a matching line, with each 
        such part on a separate output line.

这是从 MacOS 的手册页中提取的:

 -o, --only-matching
         Prints only the matching part of the lines.

虽然描述看起来有点不同,但两个选项的含义似乎相同,那么为什么 egrep -o 在 MacOS 中表现不同?我没有考虑这个命令的任何细微方面吗?

这取决于不同的 grep 实现如何处理空匹配([a-zA-Z0-9]* 匹配空字符串)。

我在 Unix 上写了 a longer text about this&Linux。

简而言之,是否应该返回所有空匹配项?这样的匹配有无数个。